Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.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为HTML树中的已知元素自动生成XPath_Xpath_Python 3.6_Auto Generate - Fatal编程技术网

使用python为HTML树中的已知元素自动生成XPath

使用python为HTML树中的已知元素自动生成XPath,xpath,python-3.6,auto-generate,Xpath,Python 3.6,Auto Generate,有没有办法(libs,而不是手动)为HTML中的已知元素生成相对XPath 假设class=“content” *** *** *** **** **** 用例: 我的想法是猜测我可能感兴趣的元素在哪里。例如标题、内容或作者。找到元素后,我希望为其生成xpath,然后使用Python3。尝试以下操作: from lxml import etree datum = """ <html> <body> <div class="title"&

有没有办法(libs,而不是手动)为HTML中的已知元素生成相对XPath

假设
class=“content”


***
***

*** ****

****

用例:
我的想法是猜测我可能感兴趣的元素在哪里。例如标题、内容或作者。找到元素后,我希望为其生成xpath,然后使用Python3。

尝试以下操作:

from lxml import etree

datum = """
<html>
    <body>
        <div class="title">
            <h1>***</h1>
        </div>
        <p> *** </p>
        <h3>***</h3>
        <div class="content">
            <p>something</p>
            <p>target</p>
        </div>
    </body>
</html>
"""

root = etree.fromstring(datum)
tree = etree.ElementTree(root)
find_text = etree.XPath("//p[text()='target']")
for target in find_text(root):
    print(tree.getpath(target))

我编写了两个chrome扩展来为元素生成xpath,但这似乎是一个特殊的要求,您需要基于其他元素获取xpath。我相信这会有点棘手,但这是可能的。Lxml是我的第一个选择,正如您在输出中看到的,XPath是绝对的,而不是相对的。似乎我必须自己构建它—类似这样的东西
from lxml import etree

datum = """
<html>
    <body>
        <div class="title">
            <h1>***</h1>
        </div>
        <p> *** </p>
        <h3>***</h3>
        <div class="content">
            <p>something</p>
            <p>target</p>
        </div>
    </body>
</html>
"""

root = etree.fromstring(datum)
tree = etree.ElementTree(root)
find_text = etree.XPath("//p[text()='target']")
for target in find_text(root):
    print(tree.getpath(target))
/html/body/div[2]/p[2]