使用 Python 的 lxml 库可以轻松地使用 XPath 方法获取 HTML 页面中 class 为 'top' 的 div 标签及其所有子元素内容。

以下示例代码展示了如何使用 lxml 库中的 xpath 方法选取 class 为 'top' 的 div 标签,并使用 tostring 方法将其转换为字符串输出:

import requests
from lxml import html

url = 'http://example.com'
response = requests.get(url)
tree = html.fromstring(response.content)

# 选取class为top的div标签
div_top = tree.xpath('//div[@class='top']')[0]

# 输出div_top及其内嵌标签的全部内容
content = html.tostring(div_top, encoding='unicode')
print(content)

其中,'//div[@class='top']' 表示选取所有 class 为 'top' 的 div 标签, '[0]' 表示选取第一个匹配的标签。html.tostring 方法将选取的标签转换为字符串,encoding='unicode' 表示输出的字符串使用 unicode 编码。

Python XPath 获取 class 为 top 的 div 标签内容

原文地址: https://www.cveoy.top/t/topic/m5cM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录