python爬蟲_微信公眾號(hào)推送信息爬取的實(shí)例
問題描述
利用搜狗的微信搜索抓取指定公眾號(hào)的最新一條推送,并保存相應(yīng)的網(wǎng)頁至本地。
注意點(diǎn)
搜狗微信獲取的地址為臨時(shí)鏈接,具有時(shí)效性。
公眾號(hào)為動(dòng)態(tài)網(wǎng)頁(JavaScript渲染),使用requests.get()獲取的內(nèi)容是不含推送消息的,這里使用selenium+PhantomJS處理
代碼
#! /usr/bin/env python3
from selenium import webdriver
from datetime import datetime
import bs4, requests
import os, time, sys
# 獲取公眾號(hào)鏈接
def getAccountURL(searchURL):
res = requests.get(searchURL)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, "lxml")
# 選擇第一個(gè)鏈接
account = soup.select('a[uigs="account_name_0"]')
return account[0]['href']
# 獲取首篇文章的鏈接,如果有驗(yàn)證碼返回None
def getArticleURL(accountURL):
browser = webdriver.PhantomJS("/Users/chasechoi/Downloads/phantomjs-2.1.1-macosx/bin/phantomjs")
# 進(jìn)入公眾號(hào)
browser.get(accountURL)
# 獲取網(wǎng)頁信息
html = browser.page_source
accountSoup = bs4.BeautifulSoup(html, "lxml")
time.sleep(1)
contents = accountSoup.find_all(hrefs=True)
try:
partitialLink = contents[0]['hrefs']
firstLink = base + partitialLink
except IndexError:
firstLink = None
print('CAPTCHA!')
return firstLink
# 創(chuàng)建文件夾存儲(chǔ)html網(wǎng)頁,以時(shí)間命名
def folderCreation():
path = os.path.join(os.getcwd(), datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
print("folder not exist!")
return path
# 將html頁面寫入本地
def writeToFile(path, account, title):
myfile = open("{}/{}_{}.html".format(path, account, title), 'wb')
myfile.write(res.content)
myfile.close()
base ='https://mp.weixin.qq.com'
accountList = ['央視新聞', '新浪新聞','鳳凰新聞','羊城晚報(bào)']
query = 'http://weixin.sogou.com/weixin?type=1&s_from=input&query='
path = folderCreation()
for index, account in enumerate(accountList):
searchURL = query + account
accountURL = getAccountURL(searchURL)
time.sleep(10)
articleURL = getArticleURL(accountURL)
if articleURL != None:
print("#{}({}/{}): {}".format(account, index+1, len(accountList), accountURL))
# 讀取第一篇文章內(nèi)容
res = requests.get(articleURL)
res.raise_for_status()
detailPage = bs4.BeautifulSoup(res.text, "lxml")
title = detailPage.title.text
print("標(biāo)題: {}\n鏈接: {}\n".format(title, articleURL))
writeToFile(path, account, title)
else:
print('{} files successfully written to {}'.format(index, path))
sys.exit()
print('{} files successfully written to {}'.format(len(accountList), path))
參考輸出
Terminal輸出

Finder

分析
鏈接獲取
首先進(jìn)入搜狗的微信搜索頁面,在地址欄中提取需要的部分鏈接,字符串連接公眾號(hào)名稱,即可生成請求鏈接
針對靜態(tài)網(wǎng)頁,利用requests獲取html文件,再用BeautifulSoup選擇需要的內(nèi)容
針對動(dòng)態(tài)網(wǎng)頁,利用selenium+PhantomJS獲取html文件,再用BeautifulSoup選擇需要的內(nèi)容
遇到驗(yàn)證碼(CAPTCHA),輸出提示。此版本代碼沒有對驗(yàn)證碼做實(shí)際處理,需要人為訪問后,再跑程序,才能避開驗(yàn)證碼。
文件寫入
使用os.path.join()構(gòu)造存儲(chǔ)路徑可以提高通用性。比如Windows路徑分隔符使用back slash(\), 而OS X 和 Linux使用forward slash(/),通過該函數(shù)能根據(jù)平臺(tái)進(jìn)行自動(dòng)轉(zhuǎn)換。
open()使用b(binary mode)參數(shù)同樣為了提高通用性(適應(yīng)Windows)
使用datetime.now()獲取當(dāng)前時(shí)間進(jìn)行命名,并通過strftime()格式化時(shí)間(函數(shù)名中的f代表format),
具體使用參考下表(摘自 Automate the Boring Stuff with Python)

以上這篇python爬蟲_微信公眾號(hào)推送信息爬取的實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python實(shí)現(xiàn)網(wǎng)站表單提交和模板
今天小編就為大家分享一篇關(guān)于Python實(shí)現(xiàn)網(wǎng)站表單提交和模板,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01
python中sub-pub機(jī)制實(shí)現(xiàn)Redis的訂閱與發(fā)布
本文主要介紹了python中sub-pub機(jī)制實(shí)現(xiàn)Redis的訂閱與發(fā)布,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03
Python3實(shí)現(xiàn)取圖片中特定的像素替換指定的顏色示例
這篇文章主要介紹了Python3實(shí)現(xiàn)取圖片中特定的像素替換指定的顏色,涉及Python3針對圖片文件的讀取、轉(zhuǎn)換、生成等相關(guān)操作技巧,需要的朋友可以參考下2019-01-01
基于python實(shí)現(xiàn)微信收紅包自動(dòng)化測試腳本(測試用例)
這篇文章主要介紹了基于python實(shí)現(xiàn)微信收紅包自動(dòng)化測試腳本,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2021-07-07

