Python里使用xpath选取class为top的div标签内包含的全部内容包括内嵌标签本身
可以使用lxml库中的xpath方法选取class为top的div标签,并使用lxml库中的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编码。
原文地址: http://www.cveoy.top/t/topic/bAZH 著作权归作者所有。请勿转载和采集!