干貨內容:[Python]抓取微信公眾號文章
優(yōu)采云 發(fā)布時(shí)間: 2020-09-01 02:09[Python]搶到微信官方賬號文章
我目前正在開(kāi)發(fā)自己的項目,該項目涉及文章,該項目需要通過(guò)python抓取微信官方帳戶(hù). 由于微信的獨特方法,不可能直接爬網(wǎng). 研究了一些文章之后,我可能會(huì )有想法. 目前,Internet可以毫無(wú)問(wèn)題地搜索提議的解決方案,但是由于第三方庫中的某些更改,內部代碼基本上無(wú)法使用. 本文是為需要爬網(wǎng)公共帳戶(hù)文章的朋友而寫(xiě)的. 最后還將提供python源代碼下載.
##公共帳戶(hù)捕獲方法
當前有兩種主流的公共帳戶(hù)爬網(wǎng)解決方案. 一種是搜索搜狗的微信官方帳戶(hù)頁(yè)面,找到文章地址,然后獲取特定的文章內容. 第二種方法是注冊一個(gè)公共帳戶(hù),然后通過(guò)官方帳戶(hù)的搜索界面可以查詢(xún)產(chǎn)品地址,然后根據該地址獲取產(chǎn)品內容.
這兩種方案各有優(yōu)缺點(diǎn). 搜狗搜索的核心思想是通過(guò)請求模擬搜狗搜索公共賬號,然后解析搜索結果頁(yè)面,然后根據公共賬號的首頁(yè)地址對抓取工具進(jìn)行爬網(wǎng). }已捕獲詳細信息. 由于搜狗與騰訊之間的協(xié)議,只能顯示最新的10個(gè)文章,但無(wú)法獲取所有文章. 如果要獲取所有文章,則朋友可能必須使用第二種方法. 第二種方法的缺點(diǎn)是通過(guò)騰訊身份驗證注冊公共帳戶(hù). 這個(gè)過(guò)程比較麻煩. 您可以通過(guò)調用該界面的公共帳戶(hù)查詢(xún)界面進(jìn)行查詢(xún),但是您需要使用硒來(lái)模擬滑動(dòng)頁(yè)面翻頁(yè)操作. 整個(gè)過(guò)程仍然很麻煩. 是. 因為我的項目不需要歷史記錄文章,所以我使用搜狗搜索功能來(lái)檢索公共帳戶(hù).
檢索最近的10個(gè)公共帳戶(hù)文章
Python需要依賴(lài)的第三方庫如下:
urllib,pyquery,請求,硒
具體邏輯寫(xiě)在注釋中,沒(méi)有什么特別復雜的.
核心爬蟲(chóng)課程
```python
#! / usr / bin / python
#代碼: utf-8
[Python]純文本視圖復制代碼
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from urllib import quote
from pyquery import PyQuery as pq
import requests
import time
import re
import os
from selenium.webdriver import Chrome
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.wait import WebDriverWait
# 搜索入口地址,以公眾為關(guān)鍵字搜索該公眾號
def get_search_result_by_keywords(sogou_search_url):
# 爬蟲(chóng)偽裝頭部設置
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0'}
# 設置操作超時(shí)時(shí)長(cháng)
timeout = 5
# 爬蟲(chóng)模擬在一個(gè)request.session中完成
s = requests.Session()
log(u'搜索地址為:%s' % sogou_search_url)
return s.get(sogou_search_url, headers=headers, timeout=timeout).content
# 獲得公眾號主頁(yè)地址
def get_wx_url_by_sougou_search_html(sougou_search_html):
doc = pq(sougou_search_html)
return doc('div[class=txt-box]')('p[class=tit]')('a').attr('href')
# 使用webdriver 加載公眾號主頁(yè)內容,主要是js渲染的部分
def get_selenium_js_html(url):
options = Options()
options.add_argument('-headless') # 無(wú)頭參數
driver = Chrome(executable_path='chromedriver', chrome_options=options)
wait = WebDriverWait(driver, timeout=10)
driver.get(url)
time.sleep(3)
# 執行js得到整個(gè)頁(yè)面內容
html = driver.execute_script("return document.documentElement.outerHTML")
driver.close()
return html
# 獲取公眾號文章內容
def parse_wx_articles_by_html(selenium_html):
doc = pq(selenium_html)
return doc('div[class="weui_media_box appmsg"]')
# 將獲取到的文章轉換為字典
def switch_arctiles_to_list(articles):
# 定義存貯變量
articles_list = []
i = 1
# 遍歷找到的文章,解析里面的內容
if articles:
for article in articles.items():
log(u'開(kāi)始整合(%d/%d)' % (i, len(articles)))
# 處理單個(gè)文章
articles_list.append(parse_one_article(article))
i += 1
return articles_list
# 解析單篇文章
def parse_one_article(article):
article_dict = {}
# 獲取標題
title = article('h4[class="weui_media_title"]').text().strip()
###log(u'標題是: %s' % title)
# 獲取標題對應的地址
url = 'http://mp.weixin.qq.com' + article('h4[class="weui_media_title"]').attr('hrefs')
log(u'地址為: %s' % url)
# 獲取概要內容
summary = article('.weui_media_desc').text()
log(u'文章簡(jiǎn)述: %s' % summary)
# 獲取文章發(fā)表時(shí)間
date = article('.weui_media_extra_info').text().strip()
log(u'發(fā)表時(shí)間為: %s' % date)
# 獲取封面圖片
pic = parse_cover_pic(article)
# 返回字典數據
return {
'title': title,
'url': url,
'summary': summary,
'date': date,
'pic': pic
}
# 查找封面圖片,獲取封面圖片地址
def parse_cover_pic(article):
pic = article('.weui_media_hd').attr('style')
p = re.compile(r'background-image:url\((.*?)\)')
rs = p.findall(pic)
log(u'封面圖片是:%s ' % rs[0] if len(rs) > 0 else '')
return rs[0] if len(rs) > 0 else ''
# 自定義log函數,主要是加上時(shí)間
def log(msg):
print u'%s: %s' % (time.strftime('%Y-%m-%d_%H-%M-%S'), msg)
# 驗證函數
def need_verify(selenium_html):
' 有時(shí)候對方會(huì )封鎖ip,這里做一下判斷,檢測html中是否包含id=verify_change的標簽,有的話(huà),代表被重定向了,提醒過(guò)一陣子重試 '
return pq(selenium_html)('#verify_change').text() != ''
# 創(chuàng )建公眾號命名的文件夾
def create_dir(keywords):
if not os.path.exists(keywords):
os.makedirs(keywords)
# 爬蟲(chóng)主函數
def run(keywords):
' 爬蟲(chóng)入口函數 '
# Step 0 : 創(chuàng )建公眾號命名的文件夾
create_dir(keywords)
# 搜狐微信搜索鏈接入口
sogou_search_url = 'http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&s_from=input&_sug_=n&_sug_type_=' % quote(
keywords)
# Step 1:GET請求到搜狗微信引擎,以微信公眾號英文名稱(chēng)作為查詢(xún)關(guān)鍵字
log(u'開(kāi)始獲取,微信公眾號英文名為:%s' % keywords)
log(u'開(kāi)始調用sougou搜索引擎')
sougou_search_html = get_search_result_by_keywords(sogou_search_url)
# Step 2:從搜索結果頁(yè)中解析出公眾號主頁(yè)鏈接
log(u'獲取sougou_search_html成功,開(kāi)始抓取公眾號對應的主頁(yè)wx_url')
wx_url = get_wx_url_by_sougou_search_html(sougou_search_html)
log(u'獲取wx_url成功,%s' % wx_url)
# Step 3:Selenium+PhantomJs獲取js異步加載渲染后的html
log(u'開(kāi)始調用selenium渲染html')
selenium_html = get_selenium_js_html(wx_url)
# Step 4: 檢測目標網(wǎng)站是否進(jìn)行了封鎖
if need_verify(selenium_html):
log(u'爬蟲(chóng)被目標網(wǎng)站封鎖,請稍后再試')
else:
# Step 5: 使用PyQuery,從Step 3獲取的html中解析出公眾號文章列表的數據
log(u'調用selenium渲染html完成,開(kāi)始解析公眾號文章')
articles = parse_wx_articles_by_html(selenium_html)
log(u'抓取到微信文章%d篇' % len(articles))
# Step 6: 把微信文章數據封裝成字典的list
log(u'開(kāi)始整合微信文章數據為字典')
articles_list = switch_arctiles_to_list(articles)
return [content['title'] for content in articles_list]
```
main入口函數:
```python
# coding: utf8
import spider_weixun_by_sogou
if __name__ == '__main__':
gongzhonghao = raw_input(u'input weixin gongzhonghao:')
if not gongzhonghao:
gongzhonghao = 'spider'
text = " ".join(spider_weixun_by_sogou.run(gongzhonghao))
print text
```
<p>直接運行main方法,然后在控制臺中輸入要爬網(wǎng)的公共帳戶(hù)的英文名稱(chēng). 中文搜索可能不止一個(gè). 此處所做的只是對精確搜索的搜索. 只需檢查電話(huà)并檢查公共帳戶(hù)號的英文,請單擊公共帳戶(hù),然后查看公共帳戶(hù)信息以查看以下與“ mask5}爬網(wǎng)的爬蟲(chóng)結果相關(guān)的信息. 您可以通過(guò)在代碼中調用webdriver.py來(lái)檢索文章的特定內容.