如何在Selenium中的XPath 1.0中为python转义单引号 [英] How to escape single quote in xpath 1.0 in selenium for python

查看:303
本文介绍了如何在Selenium中的XPath 1.0中为python转义单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在硒python脚本中使用了以下代码行:

I have the following code line used in selenium python script:

from selenium import webdriver

driver.find_element_by_xpath(u"//span[text()='" + cat2 + "']").click()

cat2是我这样得到的数据库列表中的变量:

cat2 is variable from a database list that i get like this:

db = Database()
sql = "SELECT * FROM missing
listeproduit = db.select(sql)
for record in listeproduit:
    cat2       = record[6]

问题在于变量包含如下文本:

The probleme is when the variable contain a text like this:

cat2 = Debimetre d'air

然后该脚本不起作用,因为它是非法的xpath表达式.

Then the script don't works because it's an illegal xpath expression.

通过搜索,我了解到在变量cat2中转义单引号是一个问题

From my search, i understand that it's a problem with escaping the single quote in my variable cat2

从这个答案中:用Nokogiri在XPath中转义单引号吗?

他们建议使用concat()xpath函数,但是在我的情况下如何使用它? 感谢您的帮助.

They suggest to use concat() xpath function, but how to use it in my case ? Thanks for your help.

欢呼

推荐答案

在XPath 1.0中,浏览器和Selenium都在使用XPath 1.0,没有原生的转义字符串文字的方式(在XPath 2.0中已解决). 此海报中提到的几种解决方法,其中包括:

In XPath 1.0, which is used by browsers and therefore by Selenium, there is no native way of escaping string literals (which was remedied in XPath 2.0). A few workarounds are mentioned by this poster, which includes:

  • 首先,请确保您了解可能的转义与XPath表达式中的转义之间的区别
  • 然后,如果您只需要单引号,请用双引号将其括起来,反之亦然
  • 然后,如果一个字符串文字同时包含双引号和单引号,请使用concat('"', "Here's Johnny", '"', ", said Johnny.")之类的东西,将其组合为文字:"Here's Johnny", said Johnny..
  • First off, make sure you understand the difference between escaping in Python, which is possible, and escaping within the XPath expression
  • Then, if you simply need a single quote, surround it by double quotes, and vice versa
  • Then, if one string literal contains both double and single quotes, use something like concat('"', "Here's Johnny", '"', ", said Johnny."), which combines to the literal: "Here's Johnny", said Johnny..

在您的情况下,这将起作用:

In your case, this would work:

driver.find_element_by_xpath(u"//span[text()=\"" + cat2 + "\"]").click()

解决此问题的另一种方法是设置XPath变量以包含字符串文字的值,这有助于提高可读性.但是我找不到如何使用Selenium的Web驱动程序来执行此操作,这通常意味着没有这种方法.

Another way around this is to set an XPath variable to contain the value of your string literal, which helps in readability. But I couldn't find how to do it with the web drivers for Selenium, which typically means there is no such method available.

这篇关于如何在Selenium中的XPath 1.0中为python转义单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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