webmagic+selenium模拟浏览器下载动态网页
生活随笔
收集整理的這篇文章主要介紹了
webmagic+selenium模拟浏览器下载动态网页
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
現(xiàn)在絕大多數(shù)網(wǎng)頁都是動態(tài)生成的,那么學習爬蟲就意味著更加困難。若是靜態(tài)網(wǎng)頁,只需要了解如何連接網(wǎng)絡和分析網(wǎng)頁源代碼提取標簽信息即可,但是動態(tài)網(wǎng)頁的話,就需要使用到一些特定的框架來爬取了。比較實用的爬取動態(tài)網(wǎng)頁信息的其中一個工具就是selenium了。先來看看要怎樣使用webmagic和selenium來模擬瀏覽器啟動吧。
import us.codecraft.webmagic.Spider; import us.codecraft.webmagic.downloader.selenium.SeleniumDownloader; import us.codecraft.webmagic.processor.example.GithubRepoPageProcessor;public class LiuLanQiTest {public static void main(String[] args) {// TODO Auto-generated method stub//selenium系統(tǒng)配置,其中的路徑寫自己config文件的路徑System.setProperty("selenuim_config", "D:\\jse-workspace\\WebMagicTest\\Study\\src\\main\\java\\Four\\config.ini"); Spider.create(new GithubRepoPageProcessor())//調(diào)用一個webmagic中封裝好的一個網(wǎng)頁爬取類.addUrl("http://www.baidu.com")//要爬取的網(wǎng)頁//瀏覽器驅(qū)動(動態(tài)網(wǎng)頁信息通過模擬瀏覽器啟動獲取).setDownloader(new SeleniumDownloader("D:\\ChromeDriver\\chromedriver_win32(2)\\chromedriver.exe")).thread(3)//啟動n個線程(此語句表示啟動3個線程).run();//啟動爬蟲,會阻塞當前線程執(zhí)行(及n個線程不是同時執(zhí)行的) // 。runAsync();//啟動爬蟲,當前線程繼續(xù)執(zhí)行(及n個線程同時執(zhí)行)} }當出現(xiàn)如下頁面時,說明啟動瀏覽器成功。
!!!需要注意的是,用此代碼模擬瀏覽器啟動的時候,要先將webmagic和selenium所需要的包全部導入到所建項目中,并且下載過chrome驅(qū)動。
若創(chuàng)建的項目是maven項目,則可以直接在pom.xml文件中加入如下語句:
<dependency><groupId>us.codecraft</groupId><artifactId>webmagic-core</artifactId><version>0.7.3</version></dependency><dependency><groupId>us.codecraft</groupId><artifactId>webmagic-extension</artifactId><version>0.7.3</version></dependency><dependency><groupId>us.codecraft</groupId><artifactId>webmagic-selenium</artifactId><version>0.7.3</version></dependency><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>3.0.1</version></dependency><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-chrome-driver</artifactId><version>3.0.1</version></dependency>再有就是要在所建項目下新建config配置文件,文件內(nèi)容可以參照我的config.ini文件來寫,文件內(nèi)容如下:
# What WebDriver to use for the tests #driver=phantomjs #driver=firefox driver=chrome #driver=http://localhost:8910 #driver=http://localhost:4444/wd/hub# PhantomJS specific config (change according to your installation) #phantomjs_exec_path=/Users/Bingo/bin/phantomjs-qt5 #phantomjs_exec_path=d:/phantomjs.exe chrome_exec_path=C:\Users\sky\AppData\Local\Google\Chrome\Application\chrome.exe #phantomjs_driver_path=/Users/Bingo/Documents/workspace/webmagic/webmagic-selenium/src/main.js #phantomjs_driver_loglevel=DEBUG chrome_driver_loglevel=DEBUG轉(zhuǎn)載自:https://blog.csdn.net/without_scruple/article/details/78367412
總結
以上是生活随笔為你收集整理的webmagic+selenium模拟浏览器下载动态网页的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BC807G-25 SOT-23 T/R
- 下一篇: 前端与人工智能