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之赋值,简单也不简单
Sep 24 Python
Python实现的检测网站挂马程序
Nov 30 Python
Python中字典和JSON互转操作实例
Jan 19 Python
Python的GUI框架PySide的安装配置教程
Feb 16 Python
python一键去抖音视频水印工具
Sep 14 Python
详解用python生成随机数的几种方法
Aug 04 Python
Django admin.py 在修改/添加表单界面显示额外字段的方法
Aug 22 Python
基于Python获取docx/doc文件内容代码解析
Feb 17 Python
python实现从尾到头打印单链表操作示例
Feb 22 Python
python 实现超级玛丽游戏
Nov 25 Python
用Python实现定时备份Mongodb数据并上传到FTP服务器
Jan 27 Python
用python自动生成日历
Apr 24 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实现分页的一个示例
2006/10/09 PHP
PHP伪静态页面函数附使用方法
2008/06/20 PHP
php设计模式小结
2013/02/15 PHP
为你总结一些php系统类函数
2015/10/21 PHP
详解WordPress中分类函数wp_list_categories的使用
2016/01/04 PHP
PHP substr()函数参数解释及用法讲解
2017/11/23 PHP
Dom加载让图片加载完再执行的脚本代码
2008/05/15 Javascript
EditPlus注册码生成器(js代码实现)
2013/03/25 Javascript
js实现字符串的16进制编码不加密
2014/04/25 Javascript
使用GruntJS构建Web程序之Tasks(任务)篇
2014/06/06 Javascript
用jquery的方法制作一个简单的导航栏
2014/06/23 Javascript
JavaScript AJAX之惰性载入函数
2014/08/27 Javascript
js的flv视频播放器插件使用方法
2015/06/23 Javascript
AngularGauge 属性解析详解
2016/09/06 Javascript
JavaScript中for循环的几种写法与效率总结
2017/02/03 Javascript
详解基于Angular4+ server render(服务端渲染)开发教程
2017/08/28 Javascript
vue中$set的使用(结合在实际应用中遇到的坑)
2018/07/10 Javascript
6行代码实现微信小程序页面返回顶部效果
2018/12/28 Javascript
解决vue2中使用elementUi打包报错的问题
2020/09/22 Javascript
[06:53]2018DOTA2国际邀请赛寻真——勇于创新的Vici Gaming
2018/08/14 DOTA
Python实现的读写json文件功能示例
2018/06/05 Python
python的pytest框架之命令行参数详解(下)
2019/06/27 Python
Django3.0 异步通信初体验(小结)
2019/12/04 Python
快速查找Python安装路径方法
2020/02/06 Python
大学生简历的个人自我评价
2013/12/04 职场文书
档案检查欢迎词
2014/01/13 职场文书
汉语专业毕业生自荐信
2014/07/06 职场文书
在教室放鞭炮的检讨书
2014/09/28 职场文书
2014年环境卫生工作总结
2014/11/24 职场文书
政府会议通知范文
2015/04/15 职场文书
报案材料怎么写
2015/05/25 职场文书
党员转正意见怎么写
2015/06/03 职场文书
司法廉洁教育心得体会
2016/01/20 职场文书
2019公司管理制度
2019/04/19 职场文书
python实现简易名片管理系统
2021/04/11 Python
python的netCDF4批量处理NC格式文件的操作方法
2022/03/21 Python