1. 程式人生 > >爬蟲系列5:scrapy動態頁面爬取的另一種思路

爬蟲系列5:scrapy動態頁面爬取的另一種思路

前面有篇文章給出了爬取動態頁面的一種思路,即應用Selenium+Firefox(參考《scrapy動態頁面爬取》)。但是selenium需要執行本地瀏覽器,比較耗時,不太適合大規模網頁抓取。

事實上,還有一種執行效率更高的方法。就是事先分析js發出的GET或者POST請求的網址,這樣通過python向目標地址發出同樣的請求,就可以得到與瀏覽器一致的response結果。

具體的步驟是:採用chrome瀏覽器中的除錯工具,分析網頁中用JavaScript獲取資料的request語句。具體分析步驟是:開啟監視工具(inspect)——網路(Network)——XHR(XMLHttpRequest),可以找到一個POST request對應的JavaScript或者ajax。接下來要做的就是直接對這個JavaScript或ajax做request操作,以獲取我們想要的資訊。

以下是通過傳送request,獲取response的程式碼示例:

import urllib2
import codecs
import json
 
#讀取json中所有的pid,並且生成url list
#sessionUrl ='http://buluo.qq.com/p/detail.html?bid=254116&pid='
defgetUrlList(pContent, sessionUrl):   
    posts = pContent['result']['posts']
    result = ["".join([sessionUrl,i['pid']]) for i in posts]
    return result
   
url ='http://buluo.qq.com/cgi-bin/bar/post/get_post_by_page?bid=254116&num=20&start=1980&source=2'
#注意headers應當使用dict型別,以適應request.add_header(key,value)的引數要求
#Cookie:pgv_pvi=1061844992; pgv_si=s7051931648
headers ={'Host':'buluo.qq.com',
           'Connection':'keep-alive',
           'Accept': 'application/json',
           'X-Requested-With':'XMLHttpRequest',
           'User-Agent': 'Mozilla/5.0 (WindowsNT 6.1; WOW64) AppleWebKit/537.36 '+
           '(KHTML, like Gecko)Chrome/50.0.2661.102 Safari/537.36',
           'Referer':'http://buluo.qq.com/p/barindex.html?bid=254116',
           'Accept-Language': 'zh-CN,zh;q=0.8',                   
           }
data = None
req =urllib2.Request(url, data, headers)
response =urllib2.urlopen(req)
content =response.read().decode('utf-8')
 
withcodecs.open('./content.txt', 'wb', encoding = 'utf-8', errors='ignore') as f:
         f.write(content)
 
sessionUrl ='http://buluo.qq.com/p/detail.html?bid=254116&pid='
pContent =json.loads(content);
ifpContent['result']['total'] != 0:
    print getUrlList(pContent, sessionUrl)
else:
    print "no contents in this page!"