基于selenium-java封装chrome、firefox、phantomjs实现爬虫
2017年一直以来在公司负责爬虫项目相关工程,主要业务有预定、库存、在开发中也遇到很多问题,随手记录一下,后续会持续更新。
chrome、firefox、phantomjs插件安装和版本说明
基于selenium-java封装chrome、firefox、phantomjs实现爬虫
项目下载地址
maven版本说明
org.seleniumhq.selenium selenium-java 3.5.1 com.github.detro.ghostdriver phantomjsdriver 1.1.0
chrome插件配置
下载地址:chromedriver下载地址选择本地系统对应的chrome版本安装,工程下面有一个对应的目录是:Plugin/chromedriver_win32.zip,对应chrmoe版本是SupportsChromev60-62
直接运行项目中示例
publicclassChromeTest{ publicstaticvoidmain(String[]args){ WebDriverwebDriver=null; try{ webDriver=WebDriverUtil.createChromeWebDriver("D:\\webdrvier\\chromedriver.exe");//修改路径 webDriver.get("https://www.baidu.com/"); System.out.println(webDriver.getTitle()); }catch(Exceptione){ e.printStackTrace(); }finally{ if(webDriver!=null){ webDriver.close(); } } } }
chrome配置插件是最简单的,linux上面只需要把插件换成linux版本即可
firefox
下载插件地址:geckodriver下载地址,选择本地系统对应的firefox版本安装,工程下面有一个对应的目录是:Plugin/geckodriver-v0.18.0-win64.zip,对应firefox版本是FirefoxSetup50.0(64位)、其他版本没有测试过
firefox下载地址、selenium-java版本和geckodriver版本更新迭代不一致,导致在搭建环境时很容易出现一系列问题。
直接运行项目中示例
publicclassFireFoxTest{ publicstaticvoidmain(String[]args){ WebDriverwebDriver=null; try{ webDriver=WebDriverUtil.createFirefoxWebDriver("D:\\webdrvier\\Firefox\\geckodriver_18.exe"); webDriver.get("https://book.douban.com/tag/"); SettagSet=newHashSet<>(); //获取豆瓣标签 List divWebElement=webDriver.findElements(By.cssSelector("#content>div>div.article>div:nth-child(2)>div")); for(WebElementwebElement:divWebElement){ List aWebElement=webElement.findElements(By.cssSelector("a")); for(WebElementelement:aWebElement){ tagSet.add(element.getText()); } } System.out.println(tagSet); //点击小说标签 WebElementwebElement=webDriver.findElement(By.cssSelector("#content>div>div.article>div:nth-child(2)>div:nth-child(1)>table>tbody>tr:nth-child(1)>td:nth-child(1)>a")); webElement.click(); System.out.println(webDriver.getTitle()); }catch(Exceptione){ e.printStackTrace(); }finally{ if(webDriver!=null){ webDriver.quit(); webDriver.close(); } } } }
phantomjs
下载插件地址phantomjs插件地址1、phantomjs插件地址2、下载有些慢。phantomjs是没有界面的,所以只需要下载插件即可。
直接运行项目中示例
publicclassPhantomjsTest{ publicstaticvoidmain(String[]args){ WebDriverwebDriver=null; try{ webDriver=WebDriverUtil.createPhantomjsWebDriver("D:/webdrvier/phantomjs-1.9.8-windows/phantomjs.exe"); webDriver.get("https://www.baidu.com/"); System.out.println(webDriver.getTitle()); }catch(Exceptione){ e.printStackTrace(); }finally{ if(webDriver!=null){ webDriver.close(); } } } }
到此这篇关于基于selenium-java封装chrome、firefox、phantomjs实现爬虫的文章就介绍到这了,更多相关seleniumjava封装爬虫内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。