Selenium/lxml:获取xpath
问题描述:
是否有 get_xpath
方法或方法可以在 selenium 或 lxml.html 中完成类似的操作.我有种见过面的感觉,但是在文档中找不到类似的东西.
Is there a get_xpath
method or a way to accomplish something similar in selenium or lxml.html. I have a feeling that I have seen somewhere but can't find anything like that in the docs.
伪代码说明:
browser.find_element_by_name('search[1]').get_xpath()
>>> '//*[@id="langsAndSearch"]/div[1]/form/input[1]'
答
由于元素和xpath表达式之间没有唯一的映射,因此不可能采用通用的解决方案.但是,如果您对xml/html有所了解,则可以轻松编写自己的XML/html.只是从您的元素开始,使用 parent
沿着树走,并生成您的表达式.
As there is no unique mapping between an element and an xpath expression, a general solution is not possible. But if you know something about your xml/html, it might be easy to write it your own. Just start with your element, walk up the tree using the parent
and generate your expression.