我在 selenium python 脚本中使用了以下代码行:
from selenium import webdriver
driver.find_element_by_xpath(u"//span[text()='" + cat2 + "']").click()
cat2 是来自数据库列表的变量,我是这样得到的:
db = Database()
sql = "SELECT * FROM missing
listeproduit = db.select(sql)
for record in listeproduit:
cat2 = record[6]
问题是当变量包含这样的文本时:
cat2 = Debimetre d'air
那么该脚本将无法运行,因为它是一个非法的 xpath 表达式。
根据我的搜索,我了解到在我的变量 cat2 中转义单引号是一个问题
来自这个答案:Escape single quote in XPath with Nokogiri?
他们建议使用 concat() xpath 函数,但在我的情况下如何使用它? 感谢您的帮助。
干杯
最佳答案
在浏览器和 Selenium 使用的 XPath 1.0 中,没有转义字符串文字的 native 方法(在 XPath 2.0 中已修复)。 few workarounds are mentioned by this poster ,其中包括:
- 首先,确保您了解在 Python 中转义(可能)与在 XPath 表达式中转义之间的区别
- 然后,如果您只需要一个单引号,就用双引号将其括起来,反之亦然
- 然后,如果一个字符串文字同时包含双引号和单引号,则使用类似
concat('"', "Here's Johnny", '"', ", said Johnny.")
的方法,它结合文字:"Here's Johnny", said Johnny.
。
在您的情况下,这会起作用:
driver.find_element_by_xpath(u"//span[text()=\"" + cat2 + "\"]").click()
另一种解决方法是设置一个 XPath 变量以包含字符串文字的值,这有助于提高可读性。但是我找不到如何使用 Selenium 的 Web 驱动程序来完成它,这通常意味着没有这样的方法可用。
关于python - 如何在 selenium for python 中转义 xpath 1.0 中的单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32759318/