手把手教你寫網(wǎng)絡(luò)爬蟲(5):PhantomJS實(shí)戰(zhàn)
本系列:
- 《手把手教你寫網(wǎng)絡(luò)爬蟲(1):網(wǎng)易云音樂歌單》
- 《手把手教你寫網(wǎng)絡(luò)爬蟲(2):迷你爬蟲架構(gòu)》
- 《手把手教你寫網(wǎng)絡(luò)爬蟲(3):開源爬蟲框架對比》
- 《手把手教你寫網(wǎng)絡(luò)爬蟲(4):Scrapy入門》
大家好!從今天開始,我要與大家一起打造一個屬于我們自己的分布式爬蟲平臺,同時也會對涉及到的技術(shù)進(jìn)行詳細(xì)介紹。大家如果有什么好的想法請多留言,多提意見,一起來完善我們的爬蟲平臺。在正式介紹平臺之前,先用一些篇幅對基礎(chǔ)篇做一點(diǎn)補(bǔ)充。模擬滾動
這次的目標(biāo)是爬一個眾籌網(wǎng)站的所有項(xiàng)目,項(xiàng)目列表頁如下:https://www.kaistart.com/project/more.html。打開后進(jìn)行分析,頁面顯示出10個項(xiàng)目:
如果想看到更多項(xiàng)目,并不能像網(wǎng)易云音樂那樣點(diǎn)“下一頁”翻頁,而是需要向下拉滾動條或者向下滾動鼠標(biāo)滾輪來觸發(fā)異步請求。爬蟲該如何應(yīng)對這種情況呢?我們可以使用selenium的api執(zhí)行js代碼將屏幕內(nèi)容滾動到指定位置。
下面這段代碼會一直向下滾動項(xiàng)目頁,一直到滾不動為止:
- # 一直滾動到***部
- js1 = 'return document.body.scrollHeight'
- js2 = 'window.scrollTo(0, document.body.scrollHeight)'
- old_scroll_height = 0
- while browser.execute_script(js1) >= old_scroll_height:
- old_scroll_height = browser.execute_script(js1)
- browser.execute_script(js2)
- time.sleep(1)
scrollTo() 方法可把內(nèi)容滾動到指定的坐標(biāo):
參數(shù) | 描述 |
xpos | 必需。要在窗口文檔顯示區(qū)左上角顯示的文檔的 x 坐標(biāo)。 |
ypos | 必需。要在窗口文檔顯示區(qū)左上角顯示的文檔的 y 坐標(biāo)。 |
這里用到了scrollHeight,它和ClientHeight還有OffsetHeight有什么區(qū)別呢?
- browser = webdriver.PhantomJs()
- url = 'https://www.kaistart.com/project/more.html'
- try:
- browser.get(url)
- wait = ui.WebDriverWait(browser, 20)
- wait.until(lambda dr: dr.find_element_by_class_name('project-detail').is_displayed())
- # 一直滾動到***部
- js1 = 'return document.body.scrollHeight'
- js2 = 'window.scrollTo(0, document.body.scrollHeight)'
- old_scroll_height = 0
- while browser.execute_script(js1) >= old_scroll_height:
- old_scroll_height = browser.execute_script(js1)
- browser.execute_script(js2)
- time.sleep(1)
- sel = Selector(text=browser.page_source)
- proj_list = sel.xpath('//li[@class="project-li"]')
- browser.save_screenshot(debug.png')
這樣就會把圖片保存在項(xiàng)目目錄,打開看看:
- browser = webdriver.Chrome()
再次運(yùn)行程序,不出所料,Chrome瀏覽器彈出來,不僅能夠正確顯示頁面,還一直在滾動:
項(xiàng)目全都刷出來了,想爬什么就爬吧!什么?你問我在Linux服務(wù)器上怎么爬?純命令行的那種嗎?
- from selenium import webdriver
- from pyvirtualdisplay import Display
- display = Display(visible=0, size=(800, 600))
- display.start()
- driver = webdriver.Chrome()
- driver.get("http://www.baidu.com")
- print (driver.page_source.encode('utf-8'))
- driver.quit()
- display.stop()