微信公眾號是現在信息傳播的重要平台之一,每天都有大量的文章在上面發布。但是我們並不是每個人都有時間去逐一閱讀這些文章,因此,本文將介紹如何通過編程的方式自動抓取微信公眾號文章,提取我們所需的內容。
一、抓取文章URL
要想抓取微信公眾號文章,首先需要獲取文章的URL。我們可以通過微信公眾號後台管理的接口來獲取文章的URL。
“` python
import requests
# 獲取文章URL的接口
article_url_api = ‘https://mp.weixin.qq.com/cgi-bin/appmsg’
# 輸入cookie信息和公眾號偏移量,可以獲取一定量的文章URL信息
def get_article_url_cookie(offset):
# 替換為自己的cookies信息
cookie = ‘xxx’
headers = {
‘Cookie’: cookie,
}
params = (
(‘action’, ‘list_ex’),
(‘begin’, ‘0’),
(‘count’, ‘5’),
(‘fakeid’, ‘123456’),
(‘type’, ‘9’),
(‘query’, ”),
(‘token’, ‘123456789’),
(‘lang’, ‘zh_CN’),
(‘f’, ‘json’),
(‘ajax’, ‘1’),
(‘random’, ‘0.12345678901234567’),
(‘random’, ‘0.12345678901234567’),
(‘lang’, ‘zh_CN’),
(‘created’, ‘7’),
(‘scene’, ‘124’),
(‘devicetype’, ‘Windows 10’),
(‘appmsg_token’, ‘123456789’),
(‘offset’, str(offset))
)
response = requests.get(article_url_api, headers=headers, params=params)
results = response.json().get(‘app_msg_list’)
urls = []
for res in results:
urls.append(res.get(‘link’))
return urls
# 通過公眾號偏移量,可以獲取一定量的文章URL信息
def get_article_url_by_offset():
for i in range(0, 50, 5):
urls = get_article_url_cookie(i)
print(urls)
“`
上面的代碼使用了Python的requests模塊,通過發送HTTP請求並解析相應的JSON格式數據獲取URL信息。這裡我們需要替換為自己的cookies信息和公眾號偏移量。
二、抓取文章內容
獲取文章URL之後,我們需要再次發送HTTP請求獲取文章的具體內容。這裡我們使用了Python的beautifulsoup庫,它可以方便我們解析HTML格式的網頁內容,並提取我們需要的信息。具體實現代碼如下所示:
“` python
import requests
from bs4 import BeautifulSoup
cookies = {‘key’: ‘value’} # 替換成自己的cookies信息
headers = {
‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 UBrowser/6.2.3964.2 Safari/537.36’
}
def get_article_content(url):
response = requests.get(url, headers=headers, cookies=cookies)
response.encoding = ‘utf-8’
soup = BeautifulSoup(response.text, ‘html.parser’)
title = soup.select(‘#activity-name’)[0].get_text(strip=True)
author = soup.select(‘#meta_content > span.rich_media_meta.rich_media_meta_text.rich_media_meta_nickname’)[0].get_text(strip=True)
date = soup.select(‘#meta_content > span.rich_media_meta.rich_media_meta_text’)[1].get_text(strip=True)
content = str(soup.select(‘#js_content’)[0])
return title, author, date, content
url = ‘https://mp.weixin.qq.com/s/xxxxxx’
title, author, date, content = get_article_content(url)
print(“title:”, title)
print(“author:”, author)
print(“date:”, date)
print(“content:”, content)
“`
上面的代碼中使用了#activity-name、#meta_content、#js_content等CSS選擇器獲取文章的標題、作者、發布日期、正文內容。
三、保存文章內容
抓取到文章內容之後,我們可以將文本內容保存為本地文件,以便後續的處理。這裡我們使用Python自帶的open函數,將文字內容寫入本地文件中。
“` python
import requests
from bs4 import BeautifulSoup
cookies = {‘key’: ‘value’} # 替換成自己的cookies信息
headers = {
‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 UBrowser/6.2.3964.2 Safari/537.36’
}
def get_article_content(url):
response = requests.get(url, headers=headers, cookies=cookies)
response.encoding = ‘utf-8’
soup = BeautifulSoup(response.text, ‘html.parser’)
title = soup.select(‘#activity-name’)[0].get_text(strip=True)
author = soup.select(‘#meta_content > span.rich_media_meta.rich_media_meta_text.rich_media_meta_nickname’)[0].get_text(strip=True)
date = soup.select(‘#meta_content > span.rich_media_meta.rich_media_meta_text’)[1].get_text(strip=True)
content = str(soup.select(‘#js_content’)[0])
return title, author, date, content
# 將文章轉成html格式,寫入文件
def save_article_html(title, author, date, content, filename):
with open(filename, mode=’w’, encoding=’utf-8′) as f:
f.write(f’
title: {title}
author: {author}
date: {date}
{content}’)
url = ‘https://mp.weixin.qq.com/s/xxxxxx’
title, author, date, content = get_article_content(url)
save_article_html(title, author, date, content, ‘article.html’)
“`
上面的代碼中,我們先將文章內容轉成html格式,再將其寫入到指定的文件中。
四、抓取多篇文章
獲取單篇文章是不夠的,我們需要獲取多篇文章來進行統計分析。這裡我們使用一個名為Feedparser的庫來獲取微信公眾號的RSS信息,從而獲取文章列表。具體實現代碼如下所示:
“` python
import feedparser
# 設置微信公眾號RSS地址
rss_url = “https://mp.weixin.qq.com/s?__biz=xxxxx==&mid=xxxxx==&idx=xxxxx&sn=xxxxx==&chksm=xxxxx==#wechat_redirect”
# 解析RSS信息,獲取文章列表
feed = feedparser.parse(rss_url)
urls = []
for entry in feed.entries:
url = entry.link
urls.append(url)
print(urls)
“`
上面的代碼中,我們通過解析微信公眾號的RSS信息,獲取文章列表,並將URL信息存儲到一個數組當中。
五、增加反爬蟲處理
爬蟲行為會對數據源進行一定的壓力,因此,網站會採用一些反爬蟲手段來限制我們的抓取。常見的反爬蟲手段包括:IP封禁、Cookie限制、User-Agent限制、驗證碼等。要想成功爬取數據,我們需要針對這些反爬蟲手段進行相應的處理。常見的做法包括:
1. 使用代理IP:通過使用代理IP的方式,可以避免被網站封禁IP地址
2. 修改請求頭:通過修改請求頭信息的方式,可以模擬瀏覽器的訪問,繞過網站對User-Agent、Cookie等信息的限制
3. 添加延時操作:在發送請求之間添加適當的延時操作,可以減少網站對短時間內大量請求的反爬蟲機制
“` python
import requests
from bs4 import BeautifulSoup
import time
# 獲取文章內容,增加反爬蟲處理
def get_article_content(url):
headers = {
‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 UBrowser/6.2.3964.2 Safari/537.36’,
‘Cookie’: ‘xxxxx’ # 自定義Cookie信息
}
count = 3
while count > 0:
try:
response = requests.get(url, headers=headers)
response.encoding = ‘utf-8’
soup = BeautifulSoup(response.text, ‘html.parser’)
title = soup.select(‘#activity-name’)[0].get_text(strip=True)
author = soup.select(‘#meta_content > span.rich_media_meta.rich_media_meta_text.rich_media_meta_nickname’)[0].get_text(strip=True)
date = soup.select(‘#meta_content > span.rich_media_meta.rich_media_meta_text’)[1].get_text(strip=True)
content = str(soup.select(‘#js_content’)[0])
return title, author, date, content
except:
time.sleep(2)
count -= 1
return None
url = ‘https://mp.weixin.qq.com/s/xxxxoo’
title, author, date, content = get_article_content(url)
if content:
print(“title:”, title)
print(“author:”, author)
print(“date:”, date)
print(“content:”, content)
“`
上面的代碼中,在獲取文章的過程中增加了三次重試操作,如果仍然無法獲取文章內容,則返回None。
六、小結
以上是綜合應用Python的請求庫、beautifulsoup、FeedParser等相關庫實現微信公眾號文章的抓取的方法。不過,本文只提供了如何獲取單篇文章的方法,實際應用中需要結合多線程或異步IO等技術,同時抓取多篇文章提高效率。此外,對於反爬蟲處理,需要不斷學習優化,有針對性的解決問題。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/154041.html