[英]How to deal with single and double quotes in xpath in Python
我有一个 XPath,它在 XPath 中有一个单引号,导致SyntaxError: error
。
我试过转义序列:
xpath = "//label[contains(text(),'Ayuntamiento de la Vall d'Uixó - Festivales Musix')]"
但我仍然面临一个错误:
语法错误:无法在“文档”上执行“评估”:字符串 '//label[contains(text(),'Ayuntamiento de la Vall d'Uixó - Festivales Musix')]' 不是有效的 XPath 表达式。
XPath 字符串文字中没有引号转义。 (注意:此答案适用于 XPath 1.0。在更高版本的 XPath 中,此问题已得到解决 - 请参阅下面的评论。)
在纯 XPath 中获得所需结果的唯一方法是连接交替引用的字符串。
//label[contains(., concat('Ayuntamiento de la Vall d', "'", 'Uixó - Festivales Musix'))]
您可以通过在单引号处拆分目标字符串并使用', "'" , '
作为新分隔符再次连接部分来机械地构建这些类型的表达式。 蟒蛇示例:
search_value = "Ayuntamiento de la Vall d'Uixó - Festivales Musix" # could contain both " and '
xpath = "//label[contains(., %s)]" % xpath_string_escape(search_value)
def xpath_string_escape(input_str):
""" creates a concatenation of alternately-quoted strings that is always a valid XPath expression """
parts = input_str.split("'")
return "concat('" + "', \"'\" , '".join(parts) + "', '')"
一些 XPath 库支持绑定参数(很像 SQL)来解决这个问题,但以上是唯一适用于所有地方的方法。
试试下面的xpath。
xpath = "//label[contains(text(), \"Ayuntamiento de la Vall d'Uixó - Festivales Musix\")]"
您可以使用三重引号定义搜索字符串 - 这样您就不必担心字符串中的任何潜在特殊字符和引号。
下面是一个例子:
xpath = """//label[contains(text(), "Ayuntamiento de la Vall d'Uixó - Festivales Musix")]"""
如果您还想在字符串中包含反斜杠,可以使用原始三重引号:
xpath = r"""raw triple quotes string allow the use of '\'"""
有关更多详细信息,请参阅PEP257 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.