pythom爬取微信公眾號最新部分文章(可執行程式碼)
阿新 • • 發佈:2019-02-19
執行下面的程式碼需要安裝以下內容:
pip install pyquery
pip install requests
pip install selenium
pip install pyExcelerator
pip install json
下面附上,利用微信公眾號在搜狗微信裡面搜尋得到的部分公眾號文章的爬取程式碼:
同時需要下載 phantomjs-2.1.1-windows,解壓可以直接用。
#!/usr/bin/python
# coding: utf-8
'''''
總的來說就是通過搜狗搜尋中的微信搜尋入口來爬取
2017-04-13 by Jimy_fengqi
'''
#這三行程式碼是防止在python2上面編碼錯誤的,在python3上面不要要這樣設定
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from urllib import quote
from pyquery import PyQuery as pq
from selenium import webdriver
from pyExcelerator import * #匯入excel相關包
import requests
import time
import re
import json
import os
class weixin_spider:
def __init__(self, keywords):
' 建構函式 '
self.keywords = keywords
# 搜狐微信搜尋連結入口
#self.sogou_search_url = 'http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&_sug_=n&_sug_type_=' % quote(self.keywords)
self.sogou_search_url = 'http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&s_from=input&_sug_=n&_sug_type_=' % quote(self.keywords)
# 爬蟲偽裝頭部設定
self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0'}
# 設定操作超時時長
self.timeout = 5
# 爬蟲模擬在一個request.session中完成
self.s = requests.Session()
#excel 第一行資料
self.excel_data=[u'編號',u'時間',u'文章標題',u'文章地址',u'文章簡介']
#定義excel操作控制代碼
self.excle_w=Workbook()
#搜尋入口地址,以公眾為關鍵字搜尋該公眾號
def get_search_result_by_keywords(self):
self.log(u'搜尋地址為:%s' % self.sogou_search_url)
return self.s.get(self.sogou_search_url, headers=self.headers, timeout=self.timeout).content
#獲得公眾號主頁地址
def get_wx_url_by_sougou_search_html(self, sougou_search_html):
doc = pq(sougou_search_html)
#print doc('p[class="tit"]')('a').attr('href')
#print doc('div[class=img-box]')('a').attr('href')
#通過pyquery的方式處理網頁內容,類似用beautifulsoup,但是pyquery和jQuery的方法類似,找到公眾號主頁地址
return doc('div[class=txt-box]')('p[class=tit]')('a').attr('href')
#使用webdriver 載入公眾號主頁內容,主要是js渲染的部分
def get_selenium_js_html(self, url):
browser = webdriver.PhantomJS(executable_path=r'D:\Python2.7\Scripts\phantomjs.exe')
browser.get(url)
time.sleep(3)
# 執行js得到整個頁面內容
html = browser.execute_script("return document.documentElement.outerHTML")
browser.close()
return html
#獲取公眾號文章內容
def parse_wx_articles_by_html(self, selenium_html):
doc = pq(selenium_html)
print u'開始查詢內容msg'
return doc('div[class="weui_media_box appmsg"]')
#有的公眾號僅僅有10篇文章,有的可能多一點
#return doc('div[class="weui_msg_card"]')#公眾號只有10篇文章文章的
#將獲取到的文章轉換為字典
def switch_arctiles_to_list(self, articles):
#定義存貯變數
articles_list = []
i = 1
#以當前時間為名字建表
excel_sheet_name=time.strftime('%Y-%m-%d')
excel_content=self.excle_w.add_sheet(excel_sheet_name)
#遍歷找到的文章,解析裡面的內容
if articles:
for article in articles.items():
self.log(u'開始整合(%d/%d)' % (i, len(articles)))
#處理單個文章
articles_list.append(self.parse_one_article(article,i,excel_content))
i += 1
return articles_list
#解析單篇文章
def parse_one_article(self, article,i,excel_content):
article_dict = {}
#獲取標題
title = article('h4[class="weui_media_title"]').text().strip()
self.log(u'標題是: %s' % title)
#獲取標題對應的地址
url = 'http://mp.weixin.qq.com' + article('h4[class="weui_media_title"]').attr('hrefs')
self.log(u'地址為: %s' % url)
#獲取概要內容
summary = article('.weui_media_desc').text()
self.log(u'文章簡述: %s' % summary)
#獲取文章發表時間
date = article('.weui_media_extra_info').text().strip()
self.log(u'發表時間為: %s' % date)
#獲取封面圖片
pic = self.parse_cover_pic(article)
#獲取文章內容
content = self.parse_content_by_url(url).html()
#儲存文章到本地
contentfiletitle = self.keywords+'/'+title+'_'+date+'.html'
self.save_content_file(contentfiletitle,content)
#將這些簡單的資訊儲存成excel資料
cols=0
tempContent=[i,date,title,url,summary]
for data in self.excel_data:
excel_content.write(0,cols,data)
excel_content.write(i,cols,tempContent[cols])
cols +=1
self.excle_w.save(self.keywords+'/'+self.keywords+'.xls')
#返回字典資料
return {
'title': title,
'url': url,
'summary': summary,
'date': date,
'pic': pic,
'content': content
}
#查詢封面圖片,獲取封面圖片地址
def parse_cover_pic(self, article):
pic = article('.weui_media_hd').attr('style')
p = re.compile(r'background-image:url(.∗?)')
rs = p.findall(pic)
self.log( u'封面圖片是:%s ' % rs[0] if len(rs) > 0 else '')
return rs[0] if len(rs) > 0 else ''
#獲取文章頁面詳情
def parse_content_by_url(self, url):
page_html = self.get_selenium_js_html(url)
return pq(page_html)('#js_content')
#儲存文章到本地
def save_content_file(self,title,content):
with open(title, 'w') as f:
f.write(content)
#存貯json資料到本地
def save_file(self, content):
' 資料寫入檔案 '
with open(self.keywords+'/'+self.keywords+'.txt', 'w') as f:
f.write(content)
#自定義log函式,主要是加上時間
def log(self, msg):
print u'%s: %s' % (time.strftime('%Y-%m-%d_%H-%M-%S'), msg)
#驗證函式
def need_verify(self, selenium_html):
' 有時候對方會封鎖ip,這裡做一下判斷,檢測html中是否包含id=verify_change的標籤,有的話,代表被重定向了,提醒過一陣子重試 '
return pq(selenium_html)('#verify_change').text() != ''
#建立公眾號命名的資料夾
def create_dir(self):
if not os.path.exists(self.keywords):
os.makedirs(self.keywords)
#爬蟲主函式
def run(self):
' 爬蟲入口函式 '
#Step 0 : 建立公眾號命名的資料夾
self.create_dir()
# Step 1:GET請求到搜狗微信引擎,以微信公眾號英文名稱作為查詢關鍵字
self.log(u'開始獲取,微信公眾號英文名為:%s' % self.keywords)
self.log(u'開始呼叫sougou搜尋引擎')
sougou_search_html = self.get_search_result_by_keywords()
# Step 2:從搜尋結果頁中解析出公眾號主頁連結
self.log(u'獲取sougou_search_html成功,開始抓取公眾號對應的主頁wx_url')
wx_url = self.get_wx_url_by_sougou_search_html(sougou_search_html)
self.log(u'獲取wx_url成功,%s' % wx_url)
# Step 3:Selenium+PhantomJs獲取js非同步載入渲染後的html
self.log(u'開始呼叫selenium渲染html')
selenium_html = self.get_selenium_js_html(wx_url)
# Step 4: 檢測目標網站是否進行了封鎖
if self.need_verify(selenium_html):
self.log(u'爬蟲被目標網站封鎖,請稍後再試')
else:
# Step 5: 使用PyQuery,從Step 3獲取的html中解析出公眾號文章列表的資料
self.log(u'呼叫selenium渲染html完成,開始解析公眾號文章')
articles = self.parse_wx_articles_by_html(selenium_html)
self.log(u'抓取到微信文章%d篇' % len(articles))
# Step 6: 把微信文章資料封裝成字典的list
self.log(u'開始整合微信文章資料為字典')
articles_list = self.switch_arctiles_to_list(articles)
'''''
json 資料,需要分析json資料的可以把這些註釋開啟
# Step 7: 把Step 5的字典list轉換為Json
self.log(u'整合完成,開始轉換為json')
data_json = json.dumps(articles_list)
# Step 8: 寫檔案
self.log(u'轉換為json完成,開始儲存json資料到檔案')
self.save_file(data_json)
'''
self.log(u'儲存完成,程式結束')
# main
#幾個可供參考的公眾號
#DataBureau
#python6359
#ArchNotes
if __name__ == '__main__':
print u'''''
**************************************************
** Welcome to Spider of weixin gongzhonghao **
** Created on 2017-04-13 **
** @author: Jimy _Fengqi **
**************************************************
'''
prompt=u'Please input weixin_gongzhonghao that you find:'
gongzhonghao=raw_input(prompt)
if not gongzhonghao:
gongzhonghao=u'DataBureau'
weixin_spider(gongzhonghao).run()