1. 程式人生 > >python獲取完整網頁內容(即包括js動態載入的):selenium+phantomjs

python獲取完整網頁內容(即包括js動態載入的):selenium+phantomjs

在上一篇文章(http://blog.csdn.net/Trisyp/article/details/78732630)中我們利用模擬開啟瀏覽器的方法模擬點選網頁中的載入更多來實現動態載入網頁並獲取網頁內容。但是很不幸,有些網站的這部分內容是使用js動態載入的,我們用普通方法獲取的時候,發現有些地方是空白的,所以沒法獲取Xpath,所以上篇文章方法也就失效了。
可能有些童鞋開始會認為是不是程式碼出錯了,然後列印全部網頁內容,發現想要的那部分內容確實沒有,再用瀏覽器去訪問網頁,右鍵檢視網頁原始碼發現這部分程式碼確實沒有。我就是那個傻童鞋!!!
所以本篇文章就是希望能夠解決這種問題,去抓取js動態載入的網頁。首先想到的肯定是使用selenium來呼叫瀏覽器進行抓取,但是第一句就說明了,Xpath沒法獲取,所以就沒法通過點選頁面元素來實現了。這個時候看到了這篇文章(http://blog.csdn.net/yxwb1253587469/article/details/52233562),使用selenium+phantomjs來進行無介面抓取。
具體步驟如下:
1. 下載Phantomjs,下載地址:http://phantomjs.org/
2. 下完之後直接解壓就OK了,然後selenium的安裝用pip就行了
3. 寫程式碼執行就完成了

完整程式碼如下:

import requests
from bs4 import BeautifulSoup
import re
from selenium import webdriver
import time

def getHTMLText(url):
        driver = webdriver.PhantomJS(executable_path='D:\\phantomjs-2.1.1-windows\\bin\\phantomjs')  # phantomjs的絕對路徑
time.sleep(2)
        driver.get(url)  # 獲取網頁
time.sleep(2
) return driver.page_source def fillUnivlist(html): soup = BeautifulSoup(html, 'html.parser') # 用HTML解析網址 tag = soup.find_all('div', attrs={'class': 'listInfo'}) print(str(tag[0])) return 0 def main(): url = 'http://sports.qq.com/articleList/rolls/' #要訪問的網址 html = getHTMLText(url) #獲取HTML
fillUnivlist(html) if __name__ == '__main__': main()