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

Selenium中getPageSource().contains方法是否仍受支持?

Selenium JavaScript 检测页面文本"Yes!"的正确写法

你遇到的问题是因为用了Java风格的代码逻辑,但Selenium JavaScript绑定有两处关键差异:

  1. driver.getPageSource()是异步方法,返回Promise,不能直接同步调用获取结果
  2. JavaScript字符串判断包含关系用includes()方法,而非Java里的contains()

下面是两种可行的修正方案:

方案1:使用async/await(推荐)

这种写法更直观,符合现代JS异步代码风格:

async function checkForYesText() {
  const pageSource = await driver.getPageSource();
  if (pageSource.includes("Yes!")) {
    console.log("页面包含'Yes!'");
    // 这里写文本存在时的处理逻辑
  } else {
    console.log("页面不包含'Yes!'");
    // 这里写文本不存在时的处理逻辑
  }
}

// 调用检测函数
checkForYesText();

方案2:使用Promise.then()

如果你的环境不支持async/await,可以用传统的Promise链式调用:

driver.getPageSource().then(pageSource => {
  if (pageSource.includes("Yes!")) {
    console.log("页面包含'Yes!'");
  } else {
    console.log("页面不包含'Yes!'");
  }
});

备选方案:通过查找元素检测(更可靠)

直接检查页面源码可能会包含隐藏文本或脚本内容,如果你想确认页面可见区域是否存在该文本,建议用元素定位的方式:

const { By } = require('selenium-webdriver'); // 确保引入By模块

async function checkTextVisibility() {
  try {
    // 用XPath定位包含目标文本的元素
    await driver.findElement(By.xpath("//*[contains(text(), 'Yes!')]"));
    console.log("页面存在'Yes!'文本");
  } catch (err) {
    console.log("页面不存在'Yes!'文本");
  }
}

checkTextVisibility();

内容的提问来源于stack exchange,提问作者Wayne Hazle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:05:57