admin管理员组文章数量:1665479
前言
尝试过Htmlunit和PhantomJS都无法抓取JS动态生成的页面,这两种方式实际抓取的都是原页面并不是js渲染之后的页面,后来经过尝试终于确定 Selenium + Chrome的方式能抓取js渲染之后的界面,其中也有不少坑,在这里记录一下。
一、下载chromedriver
chromedriver和谷歌版本需要严格对应
下载地址chromedriver
根据谷歌版本下载对应的chromedriver
依赖,高版本的selenium依赖只需要第一个,不用第二个依赖,但经过尝试 ,高版本的依赖可能会出现问题
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.11.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>24.1-jre</version>
</dependency>
代码
public class webdriver {
public static void main(String[] args){
System.getProperties().setProperty("webdriver.chrome.driver",
"D:\\web_driver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
// 无界面参数,使用后不会打开浏览器,linuxx环境必须加入
options.addArguments("--headless");
//禁用沙盒
options.addArguments("--no-sandbox");
options.addArguments("--disable-gpu");
options.addArguments("--disable-dev-shm-usage");
WebDriver webDriver = new ChromeDriver(options);
// webDriver.manage().window().maximize();
webDriver.get("https://www.baidu/");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(webDriver.getPageSource());
webDriver.close();
}
}
有一块代码相当重要
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
没有这段代码获取到的页面是未渲染的页面
二、linux环境
linux环境:centos7+,内核版本 _x86
centos7以下版本装不上chrome,linux内核为aarch64也装不上
查看linux内核版本
uname -a
安装chrome
配置chrome yum下载源:
在目录 /etc/yum.repos.d/ 下新建文件 google-chrome.repo
touch google-chrome.repo
在google-chrome.repo添加内容
#编辑google-chrome.repo
vi /etc/yum.repos.d/google-chrome.repo
#添加内容
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub
安装chrome
yum -y install google-chrome-stable --nogpgcheck
linux环境对不上的可能会报缺少依赖的错误
安装目录在/usr/bin/下
查看安装的chrome版本
/usr/bin/google-chrome -version
安装chromedriver
根据上面的chromedriver链接查看对应的chromedriver下载地址
#使用wget命令下载,这是85.0.4183版本谷歌对应的 driver
wget https://cdn.npm.taobao.org/dist/chromedriver/85.0.4183.87/chromedriver_linux64.zip
#使用unzip 命令解压
unzip chromedriver_linux64.zip
#将chromedriver 移至/usr/bin目录
mv chromedriver /usr/bin/chromedriver
#赋予权限
chomod 777 chromedriver
完成
!!!注意
上面的代码不能直接在liunx环境用,实用上面的代码只能获取到为渲染的页面
要获取到渲染后的页面必须在
webDriver.get("https://www.baidu/");
这段代码前加上
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
完成
欢迎访问我的个人博客
版权声明:本文标题:Java + Selenium + Chrome抓取页面元素(支持Linux环境和Windows环境) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1730043579a1220537.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论