Python資料爬蟲學習筆記(13)爬取微信文章資料
阿新 • • 發佈:2018-12-13
一、需求:在微信搜尋網站中,通過設定搜尋關鍵詞以及搜尋頁面數,爬取出所有符合條件的微信文章:
二、搜尋頁URL分析階段:
1、在搜尋框中輸入任意關鍵詞,在出現的搜尋結果頁面點選下一頁,將每一頁的URL複製下來進行觀察:
2、注意到頁碼由page=X決定,搜尋關鍵詞由query=X決定,URL中的其它變數可以通過逐個刪除測試的方式探究是否為必要變數,注意儘量不要使用QQ瀏覽器,由於QQ瀏覽器對於微信過於“智慧”,URL在錯誤的情況下仍有可能出現正常的網頁。
三、搜尋結果的元素網頁URL分析階段:
1、觀察搜尋結果頁面的原始碼:
注意到,搜尋結果的元素網頁的網址被<a target="_blank" href=".......“所包圍。
2、但是發現,原始碼中的URL開啟時(注意要通過複製URL至網址欄,再回車的方式,不要在原始碼介面點選URL開啟),會提示引數錯誤:
與手動搜尋的網頁URL比對注意到,原始碼中的URL多了”&“,刪除之後URL開啟正常,因此爬取出的URL需要搜尋出該段字元進行刪除。
四、編寫程式碼:
import re import urllib.request import time import urllib.error import urllib.request #自定義函式,功能為使用代理伺服器爬一個網址 def use_proxy(proxy_addr,url): #建立異常處理機制 try: req=urllib.request.Request(url) #瀏覽器偽裝 req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6726.400 QQBrowser/10.2.2265.400") proxy= urllib.request.ProxyHandler({'http':proxy_addr}) opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler) urllib.request.install_opener(opener) data = urllib.request.urlopen(req).read() return data except urllib.error.URLError as e: if hasattr(e,"code"): print(e.code) if hasattr(e,"reason"): print(e.reason) #若為URLError異常,延時10秒執行 time.sleep(10) except Exception as e: print("exception:"+str(e)) #若為Exception異常,延時1秒執行 time.sleep(1) #設定關鍵詞 key="Python" #設定代理伺服器,該代理伺服器有可能失效,讀者需要換成新的有效代理伺服器 proxy="127.0.0.1:8888" #爬多少頁 for i in range(0,10): key=urllib.request.quote(key) thispageurl="http://weixin.sogou.com/weixin?type=2&query="+key+"&page="+str(i) thispagedata=use_proxy(proxy,thispageurl) #檢驗是否爬取到了資料 print(len(str(thispagedata))) pat1='<a target="_blank" href="(.*?)"' rs1=re.compile(pat1,re.S).findall(str(thispagedata)) if(len(rs1)==0): print("此次("+str(i)+"頁)沒成功") continue for j in range(0,len(rs1)): thisurl=rs1[j] thisurl=thisurl.replace("amp;","") file="F:/weixin/第"+str(i)+"頁第"+str(j)+"篇文章.html" thisdata=use_proxy(proxy,thisurl) try: fh=open(file,"wb") fh.write(thisdata) fh.close() print("第"+str(i)+"頁第"+str(j)+"篇文章成功") except Exception as e: print(e) print("第"+str(i)+"頁第"+str(j)+"篇文章失敗")