lxml
是一个强大的 Python 库,用于处理 XML 和 HTML 文档。它提供了简单的 API 来解析、遍历和修改这些文档。以下是如何使用 lxml
抓取网页中的表格和 href 链接的基本步骤。
首先,你需要安装 lxml
库。你可以使用 pip 来安装:
pip install lxml
假设你有一个 HTML 页面,其中包含一个或多个表格。你可以使用 lxml
的 etree
模块来解析这个页面,并找到其中的表格。
from lxml import etree
import requests
# 获取网页内容
url = '你的网页URL'
response = requests.get(url)
html = response.content
# 解析 HTML
tree = etree.HTML(html)
# 查找所有的表格
tables = tree.xpath('//table')
for table in tables:
# 处理每个表格
rows = table.xpath('.//tr')
for row in rows:
cells = row.xpath('.//td')
for cell in cells:
print(cell.text_content().strip())
同样地,你可以使用 lxml
来查找网页中的所有 href 链接:
from lxml import etree
import requests
# 获取网页内容
url = '你的网页URL'
response = requests.get(url)
html = response.content
# 解析 HTML
tree = etree.HTML(html)
# 查找所有的 href 链接
links = tree.xpath('//a[@href]')
for link in links:
href = link.get('href')
print(href)
chardet
库来自动检测编码,或者在请求时指定正确的编码。希望这些信息对你有所帮助!
没有搜到相关的文章