微信公众号是现在信息传播的重要平台之一,每天都有大量的文章在上面发布。但是我们并不是每个人都有时间去逐一阅读这些文章,因此,本文将介绍如何通过编程的方式自动抓取微信公众号文章,提取我们所需的内容。
一、抓取文章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/n/154041.html