Selenium / lxml : Get xpath

六眼飞鱼酱① 提交于 2021-02-08 03:44:32

问题


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.

Pseudocode to illustrate:

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

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

回答1:


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.




回答2:


This trick works in 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.




回答3:


Whatever search function you use, you can reformat your search using xpath to return your element. 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?

In your example, browser.find_element_by_name('search[1]').get_xpath() would simply return '//*@name="search[1]"'. since the assumption is that your original element search returned what you were looking for.



来源:https://stackoverflow.com/questions/12788059/selenium-lxml-get-xpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!