htmlparsing: 纯净简单的 HTML 解析库

1,607 阅读1分钟

HTML Parsing

纯净的HTML解析库, 取代复杂的beautifulsoup4, pyquery, lxml

github: github.com/gaojiuli/ht…

安装

pip install htmlparsing

# or

pip install git+https://github.com/gaojiuli/htmlparsing

用法

import requests

from htmlparsing import Element

url = 'https://python.org'
r = requests.get(url)

初始化

e = Element(text=r.text, base_url=url)

获取页面中的链接

print(e.links)
"""
{...'/users/membership/', '/events/python-events', '//docs.python.org/3/tutorial/controlflow.html#defining-functions'}
"""


print(e.absolute_links)
"""
{...'https://python.org/download/alternatives',  'https://python.org/about/success/#software-development', 'https://python.org/download/other/', 'https://python.org/community/irc/'}
"""

选择器以及选择属性

print(e.xpath('//a')[0].attrs)
"""{'href': '#content', 'title': 'Skip to content'}"""

print(e.xpath('//a')[0].attrs.title)
"""Skip to content"""

print(e.css('a')[0].attrs)
"""{'href': '#content', 'title': 'Skip to content'}"""

print(e.parse('<a href="#content" title="Skip to content">{}</a>'))
"""<Result ('Skip to content',) {}>"""

获取文本内容和整个HTML

print(e.xpath('//a')[5].text)
"""PyPI"""

print(e.xpath('//a')[5].html)
"""<a href="https://pypi.python.org/" title="Python Package Index">PyPI</a>"""

print(e.xpath('//a')[5].markdown)
"""[PyPI](https://pypi.python.org/ "Python Package Index")"""

目前支持的选择器: xpath, css ,parse

github: github.com/gaojiuli/ht…