MyFirefoxDriver.java
2.14 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
package com.canrd.webmagic.processor.driver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.springframework.stereotype.Component;
/**
* @author zhongnanhuang
* @version 1.0
* @project webmagic-canrd-service
* @description 火狐浏览器驱动
* @date 2024/5/23 10:45:50
* 驱动下载地址:https://objects.githubusercontent.com/github-production-release-asset-2e65be
*/
@Component
public class MyFirefoxDriver implements BrowserDriver{
private static final String WIN_DRIVER_PATH = "D:\\driver\\firefox\\geckodriver.exe";
private static final String LINUX_DRIVER_PATH = "/home/canrd/webmagic/chrome/chromedriver-linux64/chromedriver";
@Override
public WebDriver getDriver() {
// 创建 Firefox 配置文件
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("permissions.default.image", 2); // 禁用图片加载
profile.setPreference("permissions.default.stylesheet", 2); // 禁用 CSS
profile.setPreference("media.peerconnection.enabled", false); // 禁用 WebRTC
profile.setPreference("dom.webnotifications.enabled", false); // 禁用通知
// profile.setPreference("general.useragent.override", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"); // 设置自定义 User-Agent
// 创建 Firefox 选项
FirefoxOptions options = new FirefoxOptions();
options.setProfile(profile);
String os_name = System.getProperty("os.name");
// 判断是否是windows系统
if (os_name.toLowerCase().startsWith("win")) {
// windows
// 指定 GeckoDriver 的路径
System.setProperty("webdriver.gecko.driver", WIN_DRIVER_PATH); // 替换为实际的 geckodriver 路径
} else {
// linux
System.setProperty("webdriver.chrome.driver", LINUX_DRIVER_PATH);
}
// 初始化 WebDriver
WebDriver driver = new org.openqa.selenium.firefox.FirefoxDriver(options);
return driver;
}
}