1. 程式人生 > >python學習筆記16:HTMLParser

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中儲存的結果:

原網頁表現: