Requests-HTMLPython 的 HTML 解析庫
Requests-HTML 對 Requests 進行了封裝,添加了解析 HTML 的接口,是一個 Python 的 HTML 解析庫。
我們知道 requests 只負責網絡請求,不會對響應結果進行解析,因此可以把 requests-html 理解為可以解析 HTML 文檔的 requsts 庫。requests-html 的代碼量非常少,都是基于現(xiàn)有的框架進行二次封裝,開發(fā)者使用時可更方便調用。它依賴于 PyQuery、requests、lxml 等庫。
requests-html 具有以下特性
完全支持 JavaScript
CSS 選擇器
XPath 選擇器
模擬用戶代理(如同真正的網絡瀏覽器)
自動跟蹤重定向
連接池和 cookie 持久化
安裝
pip install requests-html
使用方法
>>> from requests_html import session
# 返回一個Response對象
>>> r = session.get('https://python.org/')
# 獲取所有鏈接
>>> r.html.links
{'/users/membership/', '/about/gettingstarted/'}
# 使用css選擇器的方式獲取某個元素
>>> about = r.html.find('#about')[0]
>>> print(about.text)
About
Applications
Quotes
Getting Started
Help
Python Brochure
還有一個非常吸引人的特點是,它能將 HTML 轉換為 Markdown 文本
# 將html轉換為Markdown文本 >>> print(about.markdown) * [About](/about/) * [Applications](/about/apps/) * [Quotes](/about/quotes/) * [Getting Started](/about/gettingstarted/) * [Help](/about/help/) * [Python Brochure](http://brochure.getpython.info/)
評論
圖片
表情
