SeleniumConfig.java
3.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.canrd.webmagic.config;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
/**
* @author: xms
* @description: TODO
* @date: 2024/4/26 14:37
* @version: 1.0
*/
@Configuration
public class SeleniumConfig {
// @Bean
public WebDriver webDriver() throws InterruptedException {
// 初始化ChromeOptions
ChromeOptions options = new ChromeOptions();
// 添加代理,这里使用的代理是示例,需要替换为实际的代理服务器地址和端口
// options.addArguments("--proxy-server=http://proxy-server:port");
// 禁用JavaScript,有时这能帮助绕过Cloudflare的检查
options.addArguments("--disable-javascript");
// 禁用浏览器扩展,如果知道Cloudflare使用了特定的扩展,可以禁用它
options.addArguments("--disable-extensions");
// 禁用本地缓存,确保每次访问都从服务器获取
options.addArguments("--disable-application-cache");
// 禁止策略化
options.addArguments("--disable-infobars");
// 解决DevToolsActivePort文件不存在的报错
options.addArguments("--no-sandbox");
// 指定浏览器分辨
options.addArguments("window-size=1920x3000");
// 谷歌文档提到需要加上这个属性来规避bug
options.addArguments("--disable-gpu");
// 隐身模式(无痕模式)
options.addArguments("--incognito");
// 最大化运行(全屏窗口),不设置,取元素会报错
options.addArguments("--start-maximized");
// 禁用浏览器正在被自动化程序控制的提示
options.addArguments("--disable-infobars");
// 隐藏滚动条, 应对一些特殊页面
options.addArguments("--hide-scrollbars");
// 不加载图片, 提升速度
options.addArguments("blink-settings=imagesEnabled=false");
// 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
options.addArguments("--headless");
//禁用 blink 特征
options.addArguments("disable-blink-features=AutomationControlled");
options.setExperimentalOption("excludeSwitches", Arrays.asList("enable-automation"));
options.setExperimentalOption("useAutomationExtension", false);
options.addArguments("--remote-allow-origins=*");
String os_name = System.getProperty("os.name");
// 判断是否是windows系统
if (os_name.toLowerCase().startsWith("win")) {
// windows
options.setBinary("D:\\chrome\\chrome-headless-shell-win64\\chrome-headless-shell-win64\\chrome-headless-shell.exe");
System.setProperty("webdriver.chrome.driver", "D:\\chrome\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe");
} else {
// linux
options.setBinary("/home/canrd/webmagic/chrome/chrome-headless-shell-linux64/chrome-headless-shell");
System.setProperty("webdriver.chrome.driver", "/home/canrd/webmagic/chrome/chromedriver-linux64/chromedriver");
}
return new ChromeDriver(options);
}
}