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的Django框架完成视频处理任务的教程
Apr 02 Python
python中常用的九种预处理方法分享
Sep 11 Python
Python正则表达式使用范例分享
Dec 04 Python
Python 多维List创建的问题小结
Jan 18 Python
Python 字符串类型列表转换成真正列表类型过程解析
Aug 26 Python
使用Matplotlib 绘制精美的数学图形例子
Dec 13 Python
关于win10在tensorflow的安装及在pycharm中运行步骤详解
Mar 16 Python
python爬虫可以爬什么
Jun 16 Python
python 深度学习中的4种激活函数
Sep 18 Python
Python hashlib和hmac模块使用方法解析
Dec 08 Python
Python字符串对齐、删除字符串不需要的内容以及格式化打印字符
Jan 23 Python
python实现层次聚类的方法
Nov 01 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写出自己的BLOG系统 2
2010/04/12 PHP
php适配器模式介绍
2012/08/14 PHP
php中\r \r\n \t的区别示例介绍
2014/02/08 PHP
ThinkPHP实现ajax仿官网搜索功能实例
2014/12/02 PHP
php获取网页上所有链接的方法
2015/04/03 PHP
php中get_defined_constants函数用法实例分析
2015/05/12 PHP
PHP简单实现模拟登陆功能示例
2017/09/15 PHP
针对thinkPHP5框架存储过程bug重写的存储过程扩展类完整实例
2018/06/16 PHP
Javascript学习笔记之数组的遍历和 length 属性
2014/11/23 Javascript
jQuery控制cookie过期时间的方法
2015/04/07 Javascript
详解javascript遍历方式
2015/11/11 Javascript
AngularJS出现$http异步后台无法获取请求参数问题的解决方法
2016/11/03 Javascript
Bootstrap表单控件使用方法详解
2017/01/11 Javascript
BootStrap 标题设置跨行无效的解决方法
2017/10/25 Javascript
Angular-UI Bootstrap组件实现警报功能
2018/07/16 Javascript
原生JS实现动态加载js文件并在加载成功后执行回调函数的方法
2020/12/30 Javascript
微信小程序保存图片到相册权限设置
2020/04/09 Javascript
python利用标准库如何获取本地IP示例详解
2017/11/01 Python
Python面向对象程序设计之继承与多继承用法分析
2018/07/13 Python
python 函数内部修改外部变量的方法
2018/12/18 Python
python中logging模块的一些简单用法的使用
2019/02/22 Python
python rsync服务器之间文件夹同步脚本
2019/08/29 Python
Python读取JSON数据操作实例解析
2020/05/18 Python
用Python爬取LOL所有的英雄信息以及英雄皮肤的示例代码
2020/07/13 Python
Python如何在bool函数中取值
2020/09/21 Python
Molton Brown美国官网:奢华美容、香水、沐浴和身体护理
2020/09/02 全球购物
十周年庆典策划方案
2014/06/03 职场文书
中央空调节能方案
2014/06/15 职场文书
因公司原因离职的辞职信范文
2015/05/12 职场文书
毕业答辩开场白范文
2015/05/27 职场文书
入党自传范文2015
2015/06/26 职场文书
教育读书笔记
2015/07/02 职场文书
赞美教师的句子
2019/09/02 职场文书
创业计划书之闲置物品置换中心
2019/12/25 职场文书
PostGIS的安装与入门使用指南
2022/01/18 PostgreSQL
Python使用BeautifulSoup4修改网页内容
2022/05/20 Python