And*_*ute 7 python selenium xpath selenium-webdriver
我在selenium python脚本中使用了以下代码行:
from selenium import webdriver
driver.find_element_by_xpath(u"//span[text()='" + cat2 + "']").click()
Run Code Online (Sandbox Code Playgroud)
cat2是一个数据库列表变量,我得到这样的结果:
db = Database()
sql = "SELECT * FROM missing
listeproduit = db.select(sql)
for record in listeproduit:
cat2 = record[6]
Run Code Online (Sandbox Code Playgroud)
问题是当变量包含这样的文本时:
cat2 = Debimetre d'air
Run Code Online (Sandbox Code Playgroud)
然后脚本不起作用,因为它是非法的xpath表达式.
从我的搜索中,我知道在我的变量cat2中转义单引号是一个问题
从这个答案:使用Nokogiri在XPath中逃脱单引号?
他们建议使用concat()xpath函数,但如何在我的情况下使用它?谢谢你的帮助.
干杯
在XPath 1.0中,浏览器使用它,因此Selenium使用,没有本地方式转义字符串文字(在XPath 2.0中已经补救).一个小的解决方法是通过这张海报提及,其中包括:
concat('"', "Here's Johnny", '"', ", said Johnny.")
文字的内容:"Here's Johnny", said Johnny.
.在你的情况下,这将工作:
driver.find_element_by_xpath(u"//span[text()=\"" + cat2 + "\"]").click()
Run Code Online (Sandbox Code Playgroud)
另一种方法是设置一个XPath变量来包含字符串文字的值,这有助于提高可读性.但我找不到如何使用Selenium的Web驱动程序,这通常意味着没有这样的方法可用.
这是我刚刚编写的一个 Python 函数,它使用@Abel 的答案中描述的技巧转义要在 XPath 1.0 表达式中使用的字符串:
def escape_string_for_xpath(s):
if '"' in s and "'" in s:
return 'concat(%s)' % ", '\"',".join('"%s"' % x for x in s.split('"'))
elif '"' in s:
return "'%s'" % s
return '"%s"' % s
Run Code Online (Sandbox Code Playgroud)
请注意,它会在字符串周围添加适当类型的引号,因此请确保不要在返回值周围添加额外的引号。
使用示例:
escaped_title = escape_string_for_xpath('"that\'ll be the "day"')
driver.find_element_by_xpath('//a[@title=' + escaped_title + ']')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4508 次 |
最近记录: |