百度搜索引擎和必應搜尋引擎搜尋內容簡單爬取Python
阿新 • • 發佈:2019-02-20
這個部落格用於記錄我的計算機學習的路途,本文用於記錄Python百度搜索爬蟲編寫過程。
第一步 本程式所用的python庫
1,requests 用於GET網頁返回的資訊,這個庫比較重要。可以用來模擬瀏覽器的GET和POST,偽裝瀏覽器,成功爬取內容。比起urllib和urllib2要有很大的簡便性。
2,lxml中的etree可以通過xpath獲取爬取到的內容的特定部分。配合chrome使用會更好(chrome中有自帶的可以獲取xpath的工具。)
第二步 設計爬蟲偽裝瀏覽器
1,以下是一個頭的簡單示例。
headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, compress', 'Accept-Language': 'en-us;q=0.5,en;q=0.3', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0' }
2,可以獲取代理IP(我沒有用)
第三步 觀察百度搜索的url,獲取最初的url(word為要搜尋的關鍵詞)
baiduurl = 'http://www.baidu.com'
url = 'http://www.baidu.com.cn/s?wd=' + word + '&cl=3'
第四步 爬取內容並解析
html = requests.get(url=url,headers=headers)
path = etree.HTML(html.content)
下面是抓取部分程式碼
for i in range(1, flag): sentence = "" for j in path.xpath('//*[@id="%d"]/h3/a//text()'%((k-1)*10+i)): sentence+=j print sentence list.append(sentence)
謝謝大家