webmagic+selenium模拟浏览器下载动态网页
生活随笔
收集整理的這篇文章主要介紹了
webmagic+selenium模拟浏览器下载动态网页
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
現在絕大多數網頁都是動態生成的,那么學習爬蟲就意味著更加困難。若是靜態網頁,只需要了解如何連接網絡和分析網頁源代碼提取標簽信息即可,但是動態網頁的話,就需要使用到一些特定的框架來爬取了。比較實用的爬取動態網頁信息的其中一個工具就是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系統配置,其中的路徑寫自己config文件的路徑System.setProperty("selenuim_config", "D:\\jse-workspace\\WebMagicTest\\Study\\src\\main\\java\\Four\\config.ini"); Spider.create(new GithubRepoPageProcessor())//調用一個webmagic中封裝好的一個網頁爬取類.addUrl("http://www.baidu.com")//要爬取的網頁//瀏覽器驅動(動態網頁信息通過模擬瀏覽器啟動獲取).setDownloader(new SeleniumDownloader("D:\\ChromeDriver\\chromedriver_win32(2)\\chromedriver.exe")).thread(3)//啟動n個線程(此語句表示啟動3個線程).run();//啟動爬蟲,會阻塞當前線程執行(及n個線程不是同時執行的) // 。runAsync();//啟動爬蟲,當前線程繼續執行(及n個線程同時執行)} }當出現如下頁面時,說明啟動瀏覽器成功。
!!!需要注意的是,用此代碼模擬瀏覽器啟動的時候,要先將webmagic和selenium所需要的包全部導入到所建項目中,并且下載過chrome驅動。
若創建的項目是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配置文件,文件內容可以參照我的config.ini文件來寫,文件內容如下:
# 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轉載自:https://blog.csdn.net/without_scruple/article/details/78367412
總結
以上是生活随笔為你收集整理的webmagic+selenium模拟浏览器下载动态网页的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BC807G-25 SOT-23 T/R
- 下一篇: 判断今天是近年的第几天