简体   繁体   English

Selenium / lxml:获取xpath

[英]Selenium / lxml : Get xpath

Is there a get_xpath method or a way to accomplish something similar in selenium or lxml.html. 在selenium或lxml.html中是否有get_xpath方法或完成类似任务的方法。 I have a feeling that I have seen somewhere but can't find anything like that in the docs. 我有种见过面的感觉,但是在文档中找不到类似的东西。

Pseudocode to illustrate: 伪代码来说明:

browser.find_element_by_name('search[1]').get_xpath()

>>> '//*[@id="langsAndSearch"]/div[1]/form/input[1]'

As there is no unique mapping between an element and an xpath expression, a general solution is not possible. 由于在元素和xpath表达式之间没有唯一的映射,因此不可能有通用的解决方案。 But if you know something about your xml/html, it might be easy to write it your own. 但是,如果您对xml / html有所了解,则可以轻松编写自己的XML / html。 Just start with your element, walk up the tree using the parent and generate your expression. 只需从您的元素开始,使用parent沿树走,并生成您的表达式。

This trick works in lxml: 此技巧在lxml中有效:

In [1]: el
Out[1]: <Element span at 0x109187f50>

In [2]: el.getroottree().getpath(el)
Out[2]: '/html/body/div/table[2]/tbody/tr[1]/td[3]/table[2]/tbody/tr/td[1]/p[4]/span'

See documentation of getpath . 请参阅getpath文档。

Whatever search function you use, you can reformat your search using xpath to return your element. 无论使用什么搜索功能,都可以使用xpath重新格式化搜索以返回元素。 For instance, 例如,

driver.find_element_by_id('foo')
driver.find_element_by_xpath('//*@id="foo"')

will return exactly the same elements. 将返回完全相同的元素。

That being said, I would argue that to extend selenium with this method would be possible, but nearly pointless-- you're already providing the module with all the information it needs to find the element, why use xpath (which will almost certainly be harder to read?) to do this at all? 话虽这么说,我认为用这种方法扩展硒是可能的,但几乎没有意义-您已经为模块提供了查找元素所需的所有信息,为什么要使用xpath(几乎可以肯定是更难阅读?)完全可以做到这一点吗?

In your example, browser.find_element_by_name('search[1]').get_xpath() would simply return '//*@name="search[1]"' . 在您的示例中, browser.find_element_by_name('search[1]').get_xpath()只会返回'//*@name="search[1]"' since the assumption is that your original element search returned what you were looking for. 因为假设是您的原始元素搜索返回了您想要的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM