分享:python爬虫如何实现每天爬取微信公众号的推送文章
优采云 发布时间: 2020-12-25 13:24分享:python爬虫如何实现每天爬取微信公众号的推送文章
python爬虫如何实现每天抓取微信官方帐户的推送文章
第1部分文章如何抓取微信公众号文章
第1部分文章 python爬虫如何抓取微信公众号文章(二)
文章分别介绍了如何批量获取官方帐户的历史记录文章 url,以及如何批量抓取官方帐户的文章网址,并提取所需数据并将其保存在数据库中。
本文文章将介绍如何每天自动抓取官方帐户推送文章,然后提取数据并将其保存到数据库中。
首先介绍微信借口wxpy,wxpy基于itchat,通过大量的接口优化来提高模块的可用性,并进行丰富的功能扩展。
Wxpy可以用来接收微信官方账号推送文章,但是它只能实现获取每篇文章的标题(title),摘要(摘要),链接(url),封面图片(封面)文章。 ,我在此基础上又添加了两个属性,即文章发布时间(pub_time)和文章来源(source)
@property
def articles(self):
"""
公众号推送中的文章列表 (首篇的 标题/地址 与消息中的 text/url 相同)
其中,每篇文章均有以下属性:
* `title`: 标题
* `summary`: 摘要
* `url`: 文章 URL
* `cover`: 封面或缩略图 URL
"""
from wxpy import MP
if self.type == SHARING and isinstance(self.sender, MP):
tree = ETree.fromstring(self.raw['Content'])
# noinspection SpellCheckingInspection
items = tree.findall('.//mmreader/category/item')
article_list = list()
for item in items:
def find_text(tag):
found = item.find(tag)
if found is not None:
return found.text
article = Article()
article.title = find_text('title')
article.summary = find_text('digest')
article.url = find_text('url')
article.cover = find_text('cover')
article.pub_time = find_text('pub_time')
article.source = find_text('.//name')
article_list.append(article)
return article_list
这两个属性也应添加在article.py中:
# 发布时间
self.pub_time = None
# 来源
self.source = None
实际上,还有其他几个属性。这些属性如下,所有这些属性都可以根据需要通过ElementTree获取。
5
1
1
1566993086
100020868
1
963025857335934976
2
1
更改上述代码后,第一部分文章 python crawler如何抓取微信官方帐户文章(二) 二)中实现主要逻辑的功能,即, URL地址和发布时间作为参数传递,是令人吃惊的,而不是列表类型。
def wechat_run(self,url,pub_time): # 实现主要逻辑
# 打开数据库连接(ip/数据库用户名/登录密码/数据库名)
db = pymysql.connect("localhost", "root", "root", "weixin_database")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
html_str = self.parse_url(url)
content_list = self.get_content_list(html_str)
title = ''.join(content_list[0]["title"])
# other1 = ''.join(content_list[0]["other"])
other = '\n'.join(content_list[0]["other"])
create_time = pub_time
# print(other)
p1 = re.compile(r'\s*[(|(]20\d+[)|)]\s*[\u4e00-\u9fa5]*[\d]*[\u4e00-\u9fa5]+[\d]+号', re.S)
anhao = re.search(p1, other)
if (anhao):
anhao = anhao.group().replace("\n", "")
else:
anhao = ""
p2 = re.compile(r'\s[【]*裁判要[\u4e00-\u9fa5]\s*.*?(?=[【]|裁判文)', re.S)
zhaiyao = ''.join(re.findall(p2, other)).replace("\n", "")
# print(zhaiyao)
p3 = re.compile('.*?', re.S)
html = re.search(p3, html_str)
if (html):
html = re.search(p3, html_str).group().replace("\n", "")
else:
html = html_str.replace("\n", "")
sql = """INSERT INTO weixin_table(title,url,anhao,yaozhi,other,html,create_time,type_id)
VALUES ({},{},{},{},{},{},{},{})""".format('"' + title + '"', '"' + url + '"', '"' + anhao + '"',
'"' + zhaiyao + '"', '"' + other + '"', "'" + html + "'",
create_time, 4)
# print(sql)
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
print("数据插入成功")
except:
print("数据插入失败:")
info = sys.exc_info()
print(info[0], ":", info[1])
# 如果发生错误则回滚
db.rollback()
# 3.保存html
page_name = title
self.save_html(html, page_name)
# 关闭数据库连接
db.close()
然后编写功能以接收微信消息和官方帐户推送:
# -*- coding: utf-8 -*-
# @Time : 2019/8/29 上午8:31
# @Author : jingyoushui
# @Email : jingyoushui@163.com
# @File : wechat.py
# @Software: PyCharm
from beijing import WeixinSpider_1
from wxpy import *
import pandas as pd
bot = Bot(cache_path=True, console_qr=True)
# 打印来自其他好友、群聊和公众号的消息
@bot.register()
def print_others(msg):
print('msg:' + str(msg))
articles = msg.articles
if articles is not None:
for article in articles:
a = str(article.source)
print('title:' + str(article.title))
print('url:' + str(article.url))
print('pub_time:' + article.pub_time)
print('source:' + a)
if a != "KMTV" and a != "北京行政裁判观察":
pass
else:
content_list = []
items = []
items.append(str(article.title))
url = str(article.url)
items.append(url)
pub_time = article.pub_time
items.append(pub_time)
content_list.append(items)
name = ['title', 'link', 'create_time']
test = pd.DataFrame(columns=name, data=content_list)
if a == "KMTV":
test.to_csv("everyday_url/kmtv.csv", mode='a', encoding='utf-8')
print("保存成功")
if a == "北京行政裁判观察":
test.to_csv("everyday_url/beijing.csv", mode='a', encoding='utf-8')
print("保存成功")
weixin_spider_1 = WeixinSpider_1()
weixin_spider_1.wechat_run(url, pub_time)
if __name__ == '__main__':
# 堵塞线程
bot.join()
首先获取要抓取的官方帐户推送的文章的标题,URL,发布时间,来源等信息,并将其保存在csv文件中,然后调用WeixinSpider_1类的wechat_run函数来实现网址分析。数据提取,数据保存到数据库等操作。
在终端上运行程序,将打印出QR码,您可以通过扫描手机微信登录
操作模式是阻塞线程。它可以处于登录状态。除非您在网页上登录此帐户,否则您将被挤出并注销。
于8月30日添加: