简体   繁体   English

在 Python 中的 XPath 中添加变量

[英]Add variable in XPath in Python

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.不幸的是,在创建 XPath 时,UIAutomator 向我显示了我的电子邮件地址的文本。 I want to make XPath dynamic, so, that every time, I use that XPath, It gets the text.我想让 XPath 动态化,因此,每次我使用该 XPath 时,它都会获取文本。 Let us suppose:让我们假设:

email = 'testqatp@gmail.com'

and XPath is: XPath 是:

[@text='email']

How is that gonna work?这将如何运作?

if are talking about an input maybe an xpath like this如果正在谈论输入可能是这样的 xpath

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

give it a go :)试一试:)

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: Xpath 语言通常允许您在表达式的静态上下文中定义变量( 自 XPath 1.0 以来一直是这样), 一些xpath支持:

>>> 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 ) (这是lxml python库,基于libxml2,只支持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.不幸的是,Selenium 对 XPath 的使用只能达到浏览器内部 XPath 引擎的作用,不幸的是, XPathDOM API没有公开这些功能。 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.您必须坚持使用旧的字符串连接技巧并记住转义所有这些变量以确保它们不会破坏您的 xpath 表达式。

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

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