How do I escape an apostrophe in my XPath text query with Perl and Selenium?

我的未来我决定 提交于 2019-12-04 01:47:48

It's an XPath problem rather than the Perl problem.

The problem was discussed and answered here in great detail: http://kushalm.com/the-perils-of-xpath-expressions-specifically-escaping-quotes (broken link)

In a nutshell, modify your xquery to assemble the quote-containing string using concat()

my $perl_query = qq(span[text\(\)=concat("It","'","s a problem"]);

A couple of suggestions; hopefully at least one of them will work:

my $perl_query = qq!span[text()='It\\'s a problem']!;
my $perl_query = qq!span[text()="It's a problem"]!;

I just had the same problem and google didn't give me a satisfied solution.

I tried to substring this: value=' - ending with an Apostrophe.

My XPath that works look like:

"substring-after(., concat('value=', ''''))"

So four Apostrophes in a row.

Aditya

Well the post is quite old. But here goes my working answer for those who still come wandering around looking for escaping single apostrophe and unable to find proper answer.

Text = It's a problem

Solution xpath = //div[text()=\"It's a problem\"]

or

Solution xpath = //div[contains(text(),\"It's a\")]

Is it possible that the actual text on the web page is a curly quote and not a straight apostrophe? Also, you may have extra space at the beginning and end of the span, so that the strict equality against your string won't match.

Consider breaking up your string if possible:

my $spanValue = q/text()='It's a problem'/;
my $perlQuery = qq/span[$spanValue]/;

# $perlQuery = span[text()='It's a problem']

The solution to escaping apostrophes in xpath string literals is to double the apostrophe, e.g. qq(span[text()='It''s a problem'])

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!