Add variable in XPath in Python

泪湿孤枕 提交于 2021-01-29 09:13:10

问题


While doing automation, I have to check that email which I am entering is correct one or not. Unfortunately, while creating XPath, UIAutomator is showing me the text of my email address. I want to make XPath dynamic, so, that every time, I use that XPath, It gets the text. Let us suppose:

email = 'testqatp@gmail.com'

and XPath is:

[@text='email']

How is that gonna work?


回答1:


if are talking about an input maybe an xpath like this

xpath='//input[text()="'+email'"]'

give it a go :)




回答2:


The Xpath language normally lets you define variables in the expression's static context (this has been a thing since XPath 1.0), which some xpath libraries support:

>>> expr = "//*[local-name() = $name]"

>>> print(root.xpath(expr, name = "foo")[0].tag)
foo

>>> print(root.xpath(expr, name = "bar")[0].tag)
bar

(this is the lxml python library, based on libxml2, which only supports XPath 1.0)

Unfortunately, Selenium's use of XPath only goes as far as the browser's internal XPath engine does, and unfortunately, the DOM API for XPath does not expose these functionalities. You'll have to stick with the old string concatenation trick and remembering to escape all those variables to make sure they don't break your xpath expression.



来源:https://stackoverflow.com/questions/48083073/add-variable-in-xpath-in-python

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