python下载微信公众号相关文章


Posted in Python onFebruary 26, 2019

本文实例为大家分享了python下载微信公众号相关文章的具体代码,供大家参考,具体内容如下

目的:从零开始学自动化测试公众号中下载“pytest"一系列文档

1、搜索微信号文章关键字搜索

2、对搜索结果前N页进行解析,获取文章标题和对应URL

主要使用的是requests和bs4中的Beautifulsoup

Weixin.py

import requests
from urllib.parse import quote
from bs4 import BeautifulSoup
import re
from WeixinSpider.HTML2doc import MyHTMLParser
 
class WeixinSpider(object):
 
 def __init__(self, gzh_name, pageno,keyword):
  self.GZH_Name = gzh_name
  self.pageno = pageno
  self.keyword = keyword.lower()
  self.page_url = []
  self.article_list = []
  self.headers = {
   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'}
  self.timeout = 5
  # [...] 用来表示一组字符,单独列出:[amk] 匹配 'a','m'或'k'
  # re+ 匹配1个或多个的表达式。
  self.pattern = r'[\\/:*?"<>|\r\n]+'
 
 def get_page_url(self):
  for i in range(1,self.pageno+1):
   # https://weixin.sogou.com/weixin?query=从零开始学自动化测试&_sug_type_=&s_from=input&_sug_=n&type=2&page=2&ie=utf8
   url = "https://weixin.sogou.com/weixin?query=%s&_sug_type_=&s_from=input&_sug_=n&type=2&page=%s&ie=utf8" \
     % (quote(self.GZH_Name),i)
   self.page_url.append(url)
 
 def get_article_url(self):
  article = {}
  for url in self.page_url:
   response = requests.get(url,headers=self.headers,timeout=self.timeout)
   result = BeautifulSoup(response.text, 'html.parser')
   articles = result.select('ul[class="news-list"] > li > div[class="txt-box"] > h3 > a ')
   for a in articles:
    # print(a.text)
    # print(a["href"])
    if self.keyword in a.text.lower():
      new_text=re.sub(self.pattern,"",a.text)
      article[new_text] = a["href"]
      self.article_list.append(article)
 
 
 
headers = {'User-Agent':
      'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'}
timeout = 5
gzh_name = 'pytest文档'
My_GZH = WeixinSpider(gzh_name,5,'pytest')
My_GZH.get_page_url()
# print(My_GZH.page_url)
My_GZH.get_article_url()
# print(My_GZH.article_list)
for article in My_GZH.article_list:
 for (key,value) in article.items():
  url=value
  html_response = requests.get(url,headers=headers,timeout=timeout)
  myHTMLParser = MyHTMLParser(key)
  myHTMLParser.feed(html_response.text)
  myHTMLParser.doc.save(myHTMLParser.docfile)

HTML2doc.py

from html.parser import HTMLParser
import requests
from docx import Document
import re
from docx.shared import RGBColor
import docx
 
 
class MyHTMLParser(HTMLParser):
 def __init__(self,docname):
  HTMLParser.__init__(self)
  self.docname=docname
  self.docfile = r"D:\pytest\%s.doc"%self.docname
  self.doc=Document()
  self.title = False
  self.code = False
  self.text=''
  self.processing =None
  self.codeprocessing =None
  self.picindex = 1
  self.headers = {
   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'}
  self.timeout = 5
 
 def handle_startendtag(self, tag, attrs):
  # 图片的处理比较复杂,首先需要找到对应的图片的url,然后下载并写入doc中
  if tag == "img":
   if len(attrs) == 0:
    pass
   else:
    for (variable, value) in attrs:
     if variable == "data-type":
      picname = r"D:\pytest\%s%s.%s" % (self.docname, self.picindex, value)
      # print(picname)
     if variable == "data-src":
      picdata = requests.get(value, headers=self.headers, timeout=self.timeout)
      # print(value)
    self.picindex = self.picindex + 1
    # print(self.picindex)
    with open(picname, "wb") as pic:
     pic.write(picdata.content)
    try:
     self.doc.add_picture(picname)
    except docx.image.exceptions.UnexpectedEndOfFileError as e:
     print(e)
 
 def handle_starttag(self, tag, attrs):
  if re.match(r"h(\d)", tag):
   self.title = True
  if tag =="p":
   self.processing = tag
  if tag == "code":
   self.code = True
   self.codeprocessing = tag
 
 def handle_data(self, data):
   if self.title == True:
    self.doc.add_heading(data, level=2)
   # if self.in_div == True and self.tag == "p":
   if self.processing:
    self.text = self.text + data
   if self.code == True:
    p =self.doc.add_paragraph()
    run=p.add_run(data)
    run.font.color.rgb = RGBColor(111,111,111)
 
 def handle_endtag(self, tag):
  self.title = False
  # self.code = False
  if tag == self.processing:
   self.doc.add_paragraph(self.text)
 
   self.processing = None
   self.text=''
  if tag == self.codeprocessing:
   self.code =False

运行结果:

python下载微信公众号相关文章

缺少部分文档,如pytest文档4,是因为搜狗微信文章搜索结果中就没有

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python使用win32com在百度空间插入html元素示例
Feb 20 Python
python3 读写文件换行符的方法
Apr 09 Python
Python3实现将本地JSON大数据文件写入MySQL数据库的方法
Jun 13 Python
解决Python获取字典dict中不存在的值时出错问题
Oct 17 Python
利用python-pypcap抓取带VLAN标签的数据包方法
Jul 23 Python
PyQt5实现暗黑风格的计时器
Jul 29 Python
QML使用Python的函数过程解析
Sep 26 Python
python 实现快速生成连续、随机字母列表
Nov 28 Python
python logging添加filter教程
Dec 24 Python
np.random.seed() 的使用详解
Jan 14 Python
一文详述 Python 中的 property 语法
Sep 01 Python
Python Django路径配置实现过程解析
Nov 05 Python
python处理DICOM并计算三维模型体积
Feb 26 #Python
学习python可以干什么
Feb 26 #Python
Python3几个常见问题的处理方法
Feb 26 #Python
django 自定义过滤器的实现
Feb 26 #Python
使用Python将Mysql的查询数据导出到文件的方法
Feb 25 #Python
Python-ElasticSearch搜索查询的讲解
Feb 25 #Python
Python2 Selenium元素定位的实现(8种)
Feb 25 #Python
You might like
无法在发生错误时创建会话,请检查 PHP 或网站服务器日志,并正确配置 PHP 安装(win+linux)
2012/05/05 PHP
php+ajax导入大数据时产生的问题处理
2014/06/11 PHP
PHP的Yii框架的基本使用示例
2015/08/21 PHP
PHP判断当前使用的是什么浏览器(推荐)
2019/10/27 PHP
Javascript 中的类和闭包
2010/01/08 Javascript
JSON.parse()和JSON.stringify()使用介绍
2014/06/20 Javascript
Nodejs学习笔记之Global Objects全局对象
2015/01/13 NodeJs
js自制图片放大镜功能
2017/01/24 Javascript
Vue.js仿Metronic高级表格(二)数据渲染
2017/04/19 Javascript
Vue.js教程之axios与网络传输的学习实践
2017/04/29 Javascript
安装vue-cli报错 -4058 的解决方法
2017/10/19 Javascript
vue的一个分页组件的示例代码
2017/12/25 Javascript
vue 路由嵌套高亮问题的解决方法
2018/05/17 Javascript
微信小程序swiper实现滑动放大缩小效果
2018/11/15 Javascript
npm的lock机制解析
2019/06/20 Javascript
layer.open的自适应及居中及子页面标题的修改方法
2019/09/05 Javascript
[02:53]DOTA2英雄基础教程 山岭巨人小小
2013/12/09 DOTA
[01:20]2018DOTA2亚洲邀请赛总决赛战队LGD晋级之路
2018/04/07 DOTA
python根据时间生成mongodb的ObjectId的方法
2015/03/13 Python
自己使用总结Python程序代码片段
2015/06/02 Python
Python中字典(dict)合并的四种方法总结
2017/08/10 Python
轻松实现TensorFlow微信跳一跳的AI
2018/01/05 Python
python实现超市扫码仪计费
2018/05/30 Python
python生成ppt的方法
2018/06/07 Python
Python使用Pickle库实现读写序列操作示例
2018/06/15 Python
Python subprocess库的使用详解
2018/10/26 Python
Python代码使用 Pyftpdlib实现FTP服务器功能
2019/07/22 Python
基于PyQT实现区分左键双击和单击
2020/05/19 Python
SCDKey德国:全球领先的数字游戏市场
2019/04/09 全球购物
Pandora德国官网:购买潘多拉手链、戒指、项链和耳环
2020/02/20 全球购物
速卖通欧盟:Aliexpress EU
2020/08/19 全球购物
父母对孩子说的话
2014/04/12 职场文书
民事授权委托书范文
2014/08/02 职场文书
个人典型事迹材料
2014/12/30 职场文书
土地租赁协议书
2015/01/29 职场文书
什么是检讨书?检讨书的格式及范文
2019/11/05 职场文书