所謂微信爬蟲,即自動獲取微信的相關文章信息的一種爬蟲。
微信對我們的限制是很多的,所以我們需要采取一些手段解決這些限制
主要包括偽裝瀏覽器、使用代理IP等方式
http://weixin.sogou.com/
微信網站的限制還是很多的,當你使用你自己的IP地址去爬取的時候,大概率會出現服務器的錯誤,那是因為你的IP被封了
所以我們需要使用代理IP且偽裝瀏覽器。
首先也是同樣對網址進行分析,分析之后就能得到query后面對應的是搜索的內容page 后面對應的是頁碼。
然后分析源碼就能構造出文章的正則,之后都和前面的淘寶爬取和千圖網爬取是一樣的原理操作。
直接上代碼
import re import urllib.request import time import urllib.error #自定義函數,功能為使用代理服務器爬一個網址 def use_proxy(proxy_addr,url): #建立異常處理機制 try: req = urllib.request.Request(url) req.add_header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36") 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(1,10): key = urllib.request.quote(key) thispageurl = "http://weixin.sogou.com/weixin?query="+key+"&type=2&page="+str(i) thispagedata = use_proxy(proxy,thispageurl) print(len(str(thispagedata))) pat1 = '<a href="(.*?)"' rs1 = re.compile(pat1,re.S).findall(str(thispagedata)) #re.S .任意匹配模式 if(len(rs1) == 0): print("此次("+str(i)+"頁)沒成功") continue for j in range(0,len(rs1)): thisurl = rs1[j] thisurl = thisurl.replace("amp;","") file = "E://pythoncode/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)+"篇文章失敗")