1. 程式人生 > >[Python爬蟲] 之十五:Selenium +phantomjs根據微信公眾號抓取微信文章

[Python爬蟲] 之十五:Selenium +phantomjs根據微信公眾號抓取微信文章

頭部 drive lac 過程 標題 操作 函數 軟件測試 init

  借助搜索微信搜索引擎進行抓取

  抓取過程

  1、首先在搜狗的微信搜索頁面測試一下,這樣能夠讓我們的思路更加清晰

  技術分享

    在搜索引擎上使用微信公眾號英文名進行“搜公眾號”操作(因為公眾號英文名是公眾號唯一的,而中文名可能會有重復,同時公眾號名字一定要完全正確,不然可能搜到很多東西,這樣我們可以減少數據的篩選工作,

    只要找到這個唯一英文名對應的那條數據即可),即發送請求到‘http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&_sug_=n&_sug_type_= ‘ % ‘Python‘,並從頁面中解析出搜索結果公眾號對應的主頁跳轉鏈接。

    

  在抓取過程中用到了pyquery 也可以用xpath

  技術分享

  文件保存:

  技術分享

  完整代碼如下:

  

# coding: utf-8
# 這三行代碼是防止在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 wx_spider:
def __init__(self,Wechat_PublicID):
‘‘‘
構造函數,借助搜狗微信搜索引擎,根據微信公眾號獲取微信公眾號對應的文章的,發布時間、文章標題, 文章鏈接, 文章簡介等信息
:param Wechat_PublicID: 微信公眾號
‘‘‘
self.Wechat_PublicID = Wechat_PublicID
#搜狗引擎鏈接url
self.sogou_search_url = ‘http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&s_from=input&_sug_=n&_sug_type_=‘ % quote(Wechat_PublicID)

# 爬蟲偽裝頭部設置
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.session = requests.Session()

# excel 第一行數據
self.excel_headData = [u‘發布時間‘, u‘文章標題‘, u‘文章鏈接‘, u‘文章簡介‘]

# 定義excel操作句柄
self.excle_Workbook = Workbook()

def log(self, msg):
‘‘‘
日誌函數
:param msg: 日誌信息
:return:
‘‘‘
print u‘%s: %s‘ % (time.strftime(‘%Y-%m-%d %H-%M-%S‘), msg)

def run(self):

#Step 0 : 創建公眾號命名的文件夾
if not os.path.exists(self.Wechat_PublicID):
os.makedirs(self.Wechat_PublicID)

# 第一步 :GET請求到搜狗微信引擎,以微信公眾號英文名稱作為查詢關鍵字
self.log(u‘開始獲取,微信公眾號英文名為:%s‘ % self.Wechat_PublicID)
self.log(u‘開始調用sougou搜索引擎‘)

self.log(u‘搜索地址為:%s‘ % self.sogou_search_url)
sougou_search_html = self.session.get(self.sogou_search_url, headers=self.headers, timeout=self.timeout).content

# 第二步:從搜索結果頁中解析出公眾號主頁鏈接
doc = pq(sougou_search_html)
# 通過pyquery的方式處理網頁內容,類似用beautifulsoup,但是pyquery和jQuery的方法類似,找到公眾號主頁地址
wx_url = doc(‘div[class=txt-box]‘)(‘p[class=tit]‘)(‘a‘).attr(‘href‘)
self.log(u‘獲取wx_url成功,%s‘ % wx_url)

# 第三步:Selenium+PhantomJs獲取js異步加載渲染後的html
self.log(u‘開始調用selenium渲染html‘)
browser = webdriver.PhantomJS()
browser.get(wx_url)
time.sleep(3)
# 執行js得到整個頁面內容
selenium_html = browser.execute_script("return document.documentElement.outerHTML")
browser.close()


# 第四步: 檢測目標網站是否進行了封鎖
‘ 有時候對方會封鎖ip,這裏做一下判斷,檢測html中是否包含id=verify_change的標簽,有的話,代表被重定向了,提醒過一陣子重試 ‘
if pq(selenium_html)(‘#verify_change‘).text() != ‘‘:
self.log(u‘爬蟲被目標網站封鎖,請稍後再試‘)
else:
# 第五步: 使用PyQuery,從第三步獲取的html中解析出公眾號文章列表的數據
self.log(u‘調用selenium渲染html完成,開始解析公眾號文章‘)
doc = pq(selenium_html)

articles_list = doc(‘div[class="weui_media_box appmsg"]‘)
articlesLength = len(articles_list)
self.log(u‘抓取到微信文章%d篇‘ % articlesLength)

# Step 6: 把微信文章數據封裝成字典的list
self.log(u‘開始整合微信文章數據為字典‘)

# 遍歷找到的文章,解析裏面的內容
if articles_list:
index = 0

# 以當前時間為名字建表
excel_sheet_name = time.strftime(‘%Y-%m-%d‘)
excel_content = self.excle_Workbook.add_sheet(excel_sheet_name)
colindex = 0
columnsLength = len(self.excel_headData)
for data in self.excel_headData:
excel_content.write(0, colindex, data)
colindex += 1
for article in articles_list.items():
self.log(‘ ‘ )
self.log(u‘開始整合(%d/%d)‘ % (index, articlesLength))
index += 1
# 處理單個文章
# 獲取標題
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()
summary = article(‘p[class="weui_media_desc"]‘).text()
self.log(u‘文章簡述: %s‘ % summary)
# 獲取文章發表時間
# date = article(‘.weui_media_extra_info‘).text().strip()
date = article(‘p[class="weui_media_extra_info"]‘).text().strip()
self.log(u‘發表時間為: %s‘ % date)
# # 獲取封面圖片
# pic = article(‘.weui_media_hd‘).attr(‘style‘)
#
# p = re.compile(r‘background-image:url(.+)‘)
# rs = p.findall(pic)
# if len(rs) > 0:
# p = rs[0].replace(‘(‘, ‘‘)
# p = p.replace(‘)‘, ‘‘)
# self.log(u‘封面圖片是:%s ‘ % p)
tempContent = [date, title, url, summary]
for j in range(columnsLength):
excel_content.write(index, j, tempContent[j])

self.excle_Workbook.save(self.Wechat_PublicID + ‘/‘ + self.Wechat_PublicID + ‘.xlsx‘)

self.log(u‘保存完成,程序結束‘)

if __name__ == ‘__main__‘:

wx_spider("python6359").run()

  

[Python爬蟲] 之十五:Selenium +phantomjs根據微信公眾號抓取微信文章