Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用XPath提取特定HTML元素的值_Python_Html_Xpath_Html Parsing_Lxml - Fatal编程技术网

在Python中使用XPath提取特定HTML元素的值

在Python中使用XPath提取特定HTML元素的值,python,html,xpath,html-parsing,lxml,Python,Html,Xpath,Html Parsing,Lxml,我试过这个 url = 'http://test.ir/' content = s.get(url).content tree = html.fromstring(content) print [e.text_content() for e in tree.xpath('//div[@class="grouptext"]/text()[not(self:div)]')] 正如您在图片中看到的,我想要选定的零件: 当我使用 print [e.text_content() for e in tr

我试过这个

url = 'http://test.ir/'
content = s.get(url).content
tree = html.fromstring(content)
print [e.text_content() for e in tree.xpath('//div[@class="grouptext"]/text()[not(self:div)]')]
正如您在图片中看到的,我想要选定的零件:

当我使用

print [e.text_content() for e in tree.xpath('//div[@class="grouptext"]')]

结果还显示了所选的部分和
的内容。

假设您只需要第一次出现
标记时的
文本()
,则必须在XPath表达式中更加具体。通过添加
[1]

print [e.text_content() for e in tree.xpath('//div[@class="grouptext"][1]')]
或者,您可以通过过滤
样式
参数来选择它:

print [e.text_content() for e in tree.xpath('//div[@class="grouptext" and @style]')]
你必须决定哪条路更好。在更一般的情况下,这将取决于
标记在XML中的显示方式