在 Python 中的 XPath 中添加变量 [英] Add variable in XPath in Python

查看:43
本文介绍了在 Python 中的 XPath 中添加变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在进行自动化操作时,我必须检查我输入的电子邮件是否正确.不幸的是,在创建 XPath 时,UIAutomator 向我显示了我的电子邮件地址的文本.我想让 XPath 动态化,因此,每次我使用该 XPath 时,它都会获取文本.让我们假设:

email = 'testqatp@gmail.com'

XPath 是:

[@text='email']

这将如何运作?

解决方案

Xpath 语言通常允许您在表达式的 静态上下文(这是自 XPath 1.0),其中 一些 xpath 支持:

<预><代码>>>>expr = "///*[local-name() = $name]">>>打印(root.xpath(expr, name = "foo")[0].tag)富>>>打印(root.xpath(expr, name = "bar")[0].tag)酒吧

(这是lxml python 库,基于libxml2,仅支持XPath 1.0)

不幸的是,Selenium 使用 XPath 仅能达到浏览器内部 XPath 引擎的功能,不幸的是,DOM API for XPath 没有公开这些功能.您必须坚持使用旧的字符串连接技巧并记住转义所有这些变量以确保它们不会破坏您的 xpath 表达式.

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?

解决方案

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.

这篇关于在 Python 中的 XPath 中添加变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆