You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中处理文本包含单引号的XPath表达式

解决XPath字符串单引号嵌套导致的语法错误

你尝试的几种错误XPath写法:

  • 写法1:
    cy.xpath("`//*[contains(text(),'Didn't receive an email?')]`");
    
  • 写法2:
    cy.xpath("//*[contains(text(),'`Didn't receive an email?')`]");
    
  • 写法3:
    cy.xpath("//*[contains(text(),'Didn't receive an email?')]");
    

这些写法的核心问题是XPath字符串中的单引号(Didn't里的')和包裹文本的外层单引号冲突,导致XPath语法解析失败,出现你遇到的错误。

正确写法方案

方案1:用双引号包裹目标文本

在XPath里用双引号替代单引号包裹包含单引号的文本,同时注意JavaScript中的引号转义:

cy.xpath("//*[contains(text(),\"Didn't receive an email?\")]");

或者使用JavaScript模板字符串简化写法:

cy.xpath(`//*[contains(text(),"Didn't receive an email?")]`);

方案2:转义XPath中的单引号

在XPath语法中,单引号可以通过连续两个单引号来转义:

cy.xpath("//*[contains(text(),'Didn''t receive an email?')]");

方案3:用concat函数拼接字符串

将包含单引号的文本拆分为两部分,通过XPath的concat函数拼接:

cy.xpath("//*[contains(text(),concat('Didn','t receive an email?'))]");

内容的提问来源于stack exchange,提问作者Pulkit Agrawal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:31:04