htmlParser.py 1.6 KB
Newer Older
H
hjdhnx 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File  : htmlParser.py
# Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
# Date  : 2022/8/25

from pyquery import PyQuery as pq
from urllib.parse import urljoin

class jsoup:
    def __init__(self,MY_URL=''):
        self.MY_URL = MY_URL

    def pdfh(self,html,parse,pd=False):
H
hjdhnx 已提交
15 16
        if not parse:
            return ''
H
hjdhnx 已提交
17 18 19 20 21 22 23
        doc = pq(html)
        option = None
        if parse.find('&&') > -1:
            option = parse.split('&&')[1]
            parse = parse.split('&&')[0]

        if option:
H
hjdhnx 已提交
24
            ret = doc(parse)
H
hjdhnx 已提交
25 26 27 28 29 30
            if option == 'Text':
                ret = ret.text()
            elif option == 'Html':
                ret = ret.html()
            else:
                ret = ret.attr(option)
H
hjdhnx 已提交
31
                if pd and option in ['url','src','href','data-original','data-src']:
H
hjdhnx 已提交
32 33
                    ret = urljoin(self.MY_URL,ret)
        else:
H
hjdhnx 已提交
34 35 36 37 38 39 40
            # ret = doc(parse+':first')
            ret = doc(parse) # 由于是生成器,直接转str就能拿到第一条数据,不需要next
            # ret = ret.next()  # 取第一条数据
            # ret = doc(parse) # 下面注释的写法不对的
            # ret = ret.find(':first')
            # ret = ret.children(':first')
            ret = str(ret)
H
hjdhnx 已提交
41 42 43
        return ret

    def pdfa(self,html,parse):
H
hjdhnx 已提交
44 45
        if not parse:
            return []
H
hjdhnx 已提交
46 47 48 49 50
        doc = pq(html)
        # return [item.html() for item in doc(parse).items()]
        return [str(item) for item in doc(parse).items()]

    def pd(self,html,parse):
H
hjdhnx 已提交
51 52 53 54
        return self.pdfh(html,parse,True)

    def pq(self,html):
        return pq(html)