![](/img/trans.png)
[英]How to extract text including inline elements and the xpath to that element of the HTML page in Python
[英]How to extract text and the xpath to that element of the HTML page in Python
我正在處理一個 Django 項目,我需要將所有包含文本的元素和 xPath 提取到該元素。 例如:
<html>
<head>
<title>
The Demo page
</title>
</head>
<body>
<div>
<section>
<h1> Hello world
</h1>
</section>
<div>
<p>
Hope you all are doing well,
</p>
</div>
<div>
<p>
This is the example HTML
</p>
</div>
</div>
</body>
</html>
output 應該是這樣的:
/head/title: The Demo Page
/body/div/section/h1: Hello world!
/body/div/div[1]/p: Hope you all are doing well,
/body/div/div[2]/p: This is the example HTML
這樣的事情應該有效:
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())
Output:
/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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.