Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/84.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_Web Scraping_Lxml - Fatal编程技术网

如何在Python中将文本和xpath提取到HTML页面的该元素

如何在Python中将文本和xpath提取到HTML页面的该元素,python,html,xpath,web-scraping,lxml,Python,Html,Xpath,Web Scraping,Lxml,我正在从事一个Django项目,在这个项目中,我需要提取包含元素的所有文本以及该元素的xPath。 例如: 像这样的方法应该会奏效: from lxml import etree html = """[your html above]""" root = etree.fromstring(html) targets = root.xpath('//text()[normalize-space()]/..') tree = etree.

我正在从事一个Django项目,在这个项目中,我需要提取包含元素的所有文本以及该元素的xPath。 例如:


像这样的方法应该会奏效:

from lxml import etree
html = """[your html above]"""

root = etree.fromstring(html)
targets = root.xpath('//text()[normalize-space()]/..')
tree = etree.ElementTree(root)

for target in targets:
    print(tree.getpath(target),target.text.strip())
输出:

/html/head/title The Demo page
/html/body/div/section/h1 Hello world
/html/body/div/div[1]/p Hope you all are doing well,
/html/body/div/div[2]/p This is the example HTML

您的答案对于上面的HTML很有效,但是如果
标记中的文本类似于
这是示例HTML

我们如何将此文本作为
这是示例HTML
@ShahidTariq首先,您的示例HTML中没有
。第二,在任何情况下,这是一个不同的问题,根据StackOverflow策略,您可能应该用新的示例html将其作为另一个问题发布。谢谢!但无论如何,如果您能亲自回答这个问题,我们将不胜感激。@ShahidTariq,恐怕不行;您对问题的编辑和评论中的新问题所做的更改可能需要采用不同的方法处理所有问题。正如我所说,最好是撤销对原始问题的编辑并发布新问题。
from lxml import etree
html = """[your html above]"""

root = etree.fromstring(html)
targets = root.xpath('//text()[normalize-space()]/..')
tree = etree.ElementTree(root)

for target in targets:
    print(tree.getpath(target),target.text.strip())
/html/head/title The Demo page
/html/body/div/section/h1 Hello world
/html/body/div/div[1]/p Hope you all are doing well,
/html/body/div/div[2]/p This is the example HTML