思路:
使用搜狗搜索爬取微信文章時由於官方有反爬蟲措施,不更換代理容易被封,所以使用更換代理的方法爬取微信文章,代理池使用的是GitHub上的開源項目,地址如下:https://github.com/jhao104/proxy_pool,代理池配置參考開源項目的配置。
步驟:
1)分析網頁結構,拿到網頁請求參數
2)構造請求參數,獲取索引頁內容:
def get_index(keyword, page): data = { 'query': keyword, 'type': 2, 'page': page } queries = urlencode(data) url = base_url + queries html = get_html(url) return html
3)主要講下代理IP的實現方法,先設置本地IP為默認代理,定義獲取代理池IP地址的函數,當爬取出現403錯誤的時候更改代理,在獲取網頁源代碼的時候傳入代理IP地址,若獲取網頁源代碼失敗再次調用 get_html() 方法,再次進行獲取嘗試。
#初始化代理為本地IP
proxy = None #定義獲取代理函數
def get_proxy(): try: response = requests.get('PROXY_POOL_URL') if response.status_code == 200: return response.text return None except ConnectionError: return None #添加代理獲取網頁內容
def get_html(url, count=1): print('Crawling', url) print('Trying Count', count) global proxy if count >= MAX_COUNT: print('Tried Too Many Counts') return None try: if proxy: proxies = { 'http': 'http://' + proxy } response = requests.get(url, allow_redirects=False, headers=headers, proxies=proxies) else: response = requests.get(url, allow_redirects=False, headers=headers) if response.status_code == 200: return response.text if response.status_code == 302: # Need Proxy
print('302') proxy = get_proxy() if proxy: print('Using Proxy', proxy) return get_html(url) else: print('Get Proxy Failed') return None except ConnectionError as e: print('Error Occurred', e.args) proxy = get_proxy() count += 1
return get_html(url, count)
4)使用 pyquery 獲取詳情頁詳細微信文章信息(如:微信文章標題、內容、日期、公眾號名稱等):
def parse_detail(html): try: doc = pq(html) title = doc('.rich_media_title').text() content = doc('.rich_media_content').text() date = doc('#post-date').text() nickname = doc('#js_profile_qrcode > div > strong').text() wechat = doc('#js_profile_qrcode > div > p:nth-child(3) > span').text() return { 'title': title, 'content': content, 'date': date, 'nickname': nickname, 'wechat': wechat } except XMLSyntaxError: return None
5)存儲到MongoDB,去重操作:
def save_to_mongo(data): if db['articles'].update({'title': data['title']}, {'$set': data}, True): print('Saved to Mongo', data['title']) else: print('Saved to Mongo Failed', data['title'])
操作過程:
1)開啟代理池:
2)運行 spider.py 文件:
3) 查看保存在MongoDB的內容:
完整代碼在GitHub上:https://github.com/weixuqin/PythonProjects/tree/master/WeixinArticles
PS:當我使用配置好的默認參數文件 config.py ,並導入當前目錄下的 spider.py , 發現 pycharm 提示我錯誤,實際上並沒有出錯
原因是 pycharm 不會將當前文件目錄自動加入自己的 sourse_path ,所以需要我們手動導入:右鍵make_directory as-->sources path將當前工作的文件夾加入source_path。