记录工作:
本周为完成任务,读取网站数据,之前的认知是模拟http请求获取网页信息或者结构化数据,但本次实践困难重重,获取cookie去模拟登录,发现需要鉴权认证等操作,比较复杂。经过大神指导学习到Selenium WebDriver 尚可解决,现在任务已完成,做一下记录!
Selenium WebDriver 的介绍参考 WebDriver介绍_hzm326的博客-CSDN博客
我本次是通过WebDriver 做模拟登录,然后获取 cookie 再通过OKHTTP3 + 代理去请求结构化数据
Maven 引入:
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.5.0</version> </dependency><dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-devtools</artifactId> <version>4.0.0-rc-1</version> </dependency>
模拟浏览器登录需要下载浏览器驱动,我是用的是火狐浏览器下载驱动程序到本地geckodriver.exe
下载地址:Releases · mozilla/geckodriver · GitHub
下载好放到本地
// geckodriver.exe 绝对地址
String firefoxDriverPath = "D:\\driver\\geckodriver.exe";
// 设置指定键对值的系统属性
System.setProperty("webdriver.gecko.driver", firefoxDriverPath);
//浏览器配置
FirefoxOptions firefoxOptions = new FirefoxOptions();
//浏览器静默启动 不需要可不配置
//FirefoxBinary firefoxBinary = new FirefoxBinary();
//firefoxBinary.addCommandLineOptions("--headless");
//firefoxOptions.setBinary(firefoxBinary);
//浏览器设置代理 不需要也可不配置
//FirefoxProfile profile = new FirefoxProfile();
//profile.setPreference("network.proxy.type", 1);
//profile.setPreference("network.proxy.http", proxyIp);
//profile.setPreference("network.proxy.http_port", proxyPort);
//firefoxOptions.setProfile(profile);
//打开浏览器
WebDriver driver = new FirefoxDriver(firefoxOptions);
//设置窗口
driver.manage().window().maximize();
//打开百度
driver.get("https://www.baidu.com/");
//定位到百度的输入框,并且输入内容
By input = By.className("s_ipt");
driver.findElement(input).sendKeys("年轻人不结婚");
//浏览5秒
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
//获取Cookie
Set<Cookie> cookies = driver.manage().getCookies();
driver.close();
以上仅为参考案例,我实际获取到cookie 使用OKHTTP3 去发送post请求,获取结构化数据,并且持久化;在发送okhttp请求加上代理报错 java.lang.NoSuchMethodError:okio.BufferedSource.getBuffer()Lokio/Buffer;
再引入okio包即可解决
<dependency> <groupId>com.squareup.okio</groupId> <artifactId>okio</artifactId> <version>2.10.0</version> </dependency>
如果获取的不是结构化数据,直接获取页面数据通过
//获取页面数据
String pageSource = driver.getPageSource();
Document document =Jsoup.parse(pageSource);
JSoup 参考 Jsoup详解_乐天_米豆的博客-CSDN博客_jsoup
工作日常做个记录,各位大佬请多多指教