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虚拟环境virualenv的安装与使用
Dec 18 Python
python爬虫基本知识
Mar 05 Python
Python实现去除图片中指定颜色的像素功能示例
Apr 13 Python
eclipse创建python项目步骤详解
May 10 Python
Python Web框架之Django框架Form组件用法详解
Aug 16 Python
Python3之字节串bytes与字节数组bytearray的使用详解
Aug 27 Python
Python之Numpy的超实用基础详细教程
Oct 23 Python
python3 tkinter实现添加图片和文本
Nov 26 Python
python opencv图片编码为h264文件的实例
Dec 12 Python
解决python和pycharm安装gmpy2 出现ERROR的问题
Aug 28 Python
Python函数中apply、map、applymap的区别
Nov 27 Python
Python借助with语句实现代码段只执行有限次
Mar 23 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 mail()函数使用及配置方法
2014/01/14 PHP
PHP生成指定长度随机数最简洁的方法
2014/07/14 PHP
PHP实现的二分查找算法实例分析
2017/12/19 PHP
javascript算法题 求任意一个1-9位不重复的N位数在该组合中的大小排列序号
2012/07/21 Javascript
让元素在网页中可拖动示例代码
2013/08/13 Javascript
js判断元素是否隐藏的方法
2014/06/09 Javascript
用Node.js通过sitemap.xml批量抓取美女图片
2015/05/28 Javascript
js实现异步循环实现代码
2016/02/16 Javascript
Bootstrap入门书籍之(四)菜单、按钮及导航
2016/02/17 Javascript
Node.js环境下编写爬虫爬取维基百科内容的实例分享
2016/06/12 Javascript
Vue2.0实现调用摄像头进行拍照功能 exif.js实现图片上传功能
2018/04/28 Javascript
详解JavaScript 中 if / if...else...替换方式
2018/07/15 Javascript
javascript利用键盘控制小方块的移动
2020/04/20 Javascript
javascript实现页面的实时时钟显示示例
2020/08/06 Javascript
python访问纯真IP数据库的代码
2011/05/19 Python
使用Python编写类UNIX系统的命令行工具的教程
2015/04/15 Python
django自带的server 让外网主机访问方法
2018/05/14 Python
python 利用for循环 保存多个图像或者文件的实例
2018/11/09 Python
使用 Python 玩转 GitHub 的贡献板(推荐)
2019/04/04 Python
Python实现的爬取百度贴吧图片功能完整示例
2019/05/10 Python
Python基础知识点 初识Python.md
2019/05/14 Python
wxPython实现文本框基础组件
2019/11/18 Python
使用python-opencv读取视频,计算视频总帧数及FPS的实现
2019/12/10 Python
解决TensorFlow调用Keras库函数存在的问题
2020/07/06 Python
Python迭代器协议及for循环工作机制详解
2020/07/14 Python
应届毕业生自我鉴定范文
2013/12/27 职场文书
弘扬雷锋精神活动演讲稿
2014/03/04 职场文书
项目施工员岗位职责
2014/03/09 职场文书
初三学习计划书范文
2014/04/30 职场文书
致运动员赞词
2015/07/22 职场文书
学风建设主题班会
2015/08/17 职场文书
如何用JavaScipt测网速
2021/05/09 Javascript
Java各种比较对象的方式的对比总结
2021/06/20 Java/Android
Python编写nmap扫描工具
2021/07/21 Python
Flutter集成高德地图并添加自定义Maker的实践
2022/04/07 Java/Android
分享python函数常见关键字
2022/04/26 Python