querylist采集微信公眾號文章(搜狗搜索有個(gè)不足實(shí)現公眾號的爬蟲(chóng)需要安裝 )
優(yōu)采云 發(fā)布時(shí)間: 2022-02-14 04:15querylist采集微信公眾號文章(搜狗搜索有個(gè)不足實(shí)現公眾號的爬蟲(chóng)需要安裝
)
因為搜狗搜索有微信公眾號搜索的接口,所以可以通過(guò)這個(gè)接口實(shí)現公眾號的爬蟲(chóng)。
需要安裝幾個(gè)python庫:selenium、pyquery
我們也用到了phantomjs.exe,需要自己下載,然后放到我們自己的python項目下。
在輸入框中輸入你要爬取的公眾號的微信號,然后搜索公眾號,
可以出現搜索結果,進(jìn)入首頁(yè)可以看到公眾號最近發(fā)布的文章,點(diǎn)擊標題查看文章的內容
這種思路,可以在網(wǎng)頁(yè)上查看微信公眾號的推送,實(shí)現公眾號爬蟲(chóng);但搜狗搜索有個(gè)缺點(diǎn),只能查看公眾號最近發(fā)布的10條推送,無(wú)法查看過(guò)去的歷史記錄。
有了爬蟲(chóng)思路后,就開(kāi)始執行流程,先拿到搜狗搜索的接口
通過(guò)這個(gè)接口可以得到公眾號首頁(yè)的入口,文章列表,文章內容,用python寫(xiě)爬蟲(chóng)的實(shí)現,下面是運行結果,得到< @文章 標題、文章 鏈接、文章 簡(jiǎn)要說(shuō)明、發(fā)表時(shí)間、封面圖片鏈接、文章 內容,并將抓取的信息保存到文本文檔中,文章@ > 公眾號爬取結束。
廢話(huà)不多說(shuō),代碼如下:
from pyquery import PyQuery as pq
from selenium import webdriver
import os
import re
import requests
import time
# 使用webdriver 加載公眾號主頁(yè)內容,主要是js渲染的部分
def get_selenium_js_html(url):
browser = webdriver.PhantomJS(executable_path=r'phantomjs.exe')
browser.get(url)
time.sleep(3)
# 執行js得到整個(gè)頁(yè)面內容
html = browser.execute_script("return document.documentElement.outerHTML")
browser.close()
return html
def log(msg):
print('%s: %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), msg))
# 創(chuàng )建公眾號命名的文件夾
def create_dir():
if not os.path.exists(keyword):
os.makedirs(keyword)
# 將獲取到的文章轉換為字典
def switch_articles_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))
i += 1
return articles_list
# 解析單篇文章
def parse_one_article(article, i):
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)
# 獲取文章內容(pyQuery.text / html)
#log('content是')
#log(parse_content_by_url(url))
content = parse_content_by_url(url).text()
log('獲取到content')
# 存儲文章到本地
#content_file_title = keyword + '/' + str(i) + '_' + title + '_' + date + '.html'
#with open(content_file_title, 'w', encoding='utf-8') as f:
# f.write(content)
content_title = keyword + '/' + keyword + '.txt'
with open(content_title, 'a', encoding='utf-8') as f:
print('第', i, '條', file=f)
print('title:', title, file=f)
print('url:', url, file=f)
print('summary:', summary, file=f)
print('date:', date, file=f)
print('pic:', pic, file=f)
print('content:', content, file=f)
print(file=f)
log('寫(xiě)入content')
article_dict = {
'title': title,
'url': url,
'summary': summary,
'date': date,
'pic': pic,
'content': content
}
return article_dict
# 查找封面圖片,獲取封面圖片地址
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 ''
# 獲取文章頁(yè)面詳情
def parse_content_by_url(url):
page_html = get_selenium_js_html(url)
return pq(page_html)('#js_content')
'''程序入口'''
keyword = 'python'
create_dir()
url = 'http://weixin.sogou.com/weixin?query=%s' % keyword
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0'}
try:
log(u'開(kāi)始調用sougou搜索引擎')
r = requests.get(url, headers=headers)
r.raise_for_status()
print(r.status_code)
print(r.request.url)
print(len(r.text))
#print(r.text)
#print(re.Session().get(url).text)
except:
print('爬取失敗')
# 獲得公眾號主頁(yè)地址
doc = pq(r.text)
log(u'獲取sougou_search_html成功,開(kāi)始抓取公眾號對應的主頁(yè)wx_url')
home_url = doc('div[class=txt-box]')('p[class=tit]')('a').attr('href')
log(u'獲取wx_url成功,%s' % home_url)
# 使用webdriver 加載公眾號主頁(yè)內容,主要是js渲染的部分
log(u'開(kāi)始調用selenium渲染公眾號主頁(yè)html')
html = get_selenium_js_html(home_url)
#有時(shí)候對方會(huì )封鎖ip,這里做一下判斷,檢測html中是否包含id=verify_change的標簽,有的話(huà),代表被重定向了,提醒過(guò)一陣子重試
if pq(html)('#verify_change').text() != '':
log(u'爬蟲(chóng)被目標網(wǎng)站封鎖,請稍后再試')
else:
log(u'調用selenium渲染html完成,開(kāi)始解析公眾號文章')
doc = pq(html)
articles = doc('div[class="weui_media_box appmsg"]')
#print(articles)
log(u'抓取到微信文章%d篇' % len(articles))
article_list = switch_articles_to_list(articles)
print(article_list)
log('程序結束')