python学习笔记16:HTMLParser

目的:将我喜欢的公众号文章保存为Word,以方便阅读,使用html.parser中的HTMLParser对网页进行解析,并使用docx中的Document将解析结果保存到word中

HTMLParser类定义及常用方法
标准库中的定义
class html.parser.HTMLParser(*, convert_charrefs=True)
HTMLParser主要是用来解析HTML文件(包括HTML中无效的标记)
参数convert_charrefs表示是否将所有的字符引用自动转化为Unicode形式,Python3.5以后默认是True
HTMLParser可以接收相应的HTML内容,并进行解析,遇到HTML的标签会自动调用相应的handler(处理方法)来处理,
用户需要自己创建相应的子类来继承HTMLParser,并且复写相应的handler方法
HTMLParser不会检查开始标签和结束标签是否是一对
常用方法
HTMLParser.feed(data):接收一个字符串类型的HTML内容,并进行解析
HTMLParser.handle_starttag(tag, attrs):对开始标签的处理方法。例如<div id="main">,参数tag指的是div,attrs指的是一个(name,Value)的列表
HTMLParser.handle_endtag(tag):对结束标签的处理方法。例如</div>,参数tag指的是div
HTMLParser.handle_data(data):对标签之间的数据的处理方法。<tag>test</tag>,data指的是“test”
HTMLParser.handle_comment(data):对HTML中注释的处理方法。

from html.parser import HTMLParser
import requests
from docx import Document
import re
from docx.shared import RGBColor


class MyHTMLParser(HTMLParser):
    def __init__(self,docname):
        HTMLParser.__init__(self)
        self.docname=docname
        self.docfile = r"D:\%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:\%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)
                self.doc.add_picture(picname)

    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


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
url="https://mp.weixin.qq.com/s?timestamp=1543665897&src=3&ver=1&signature=1NoNLad0ojNB9P7tt3Ma8sWj3YizZw*3GJDY*7otqYs2xcd5Ux*O4z8lBD1L2HKSoyYvW838hzMzL1W8f7pTdbWiA5zvdzixE38QjxQa*Hi85IMOgbtwjLPuUEYeAq-EbjSio4Sx7j0sCkF1Twl1kc*a-9sI8u-EYfpNokaox64="
html_response = requests.get(url,headers=headers,timeout=timeout)
myHTMLParser = MyHTMLParser("python测试开发django-6.模板中include使用")
myHTMLParser.feed(html_response.text)
myHTMLParser.doc.save(myHTMLParser.docfile)

运行结果:

word中保存的结果:

原网页表现:

猜你喜欢

转载自blog.csdn.net/yaoliuwei1426/article/details/84678164