如何用JavaScript实现页面指定文本检测?附Python参考代码
如何用JavaScript检查页面中是否存在指定文本
嘿,刚好可以帮你把Python的Selenium代码转换成对应的JavaScript版本,分两种常用场景给你说明:
一、Selenium Node.js 版本(和你的Python逻辑完全对应)
首先得确保你已经装好了Selenium的Node.js包和Chrome驱动,先执行安装命令:
npm install selenium-webdriver
然后是具体代码:
const { Builder } = require('selenium-webdriver'); const chrome = require('selenium-webdriver/chrome'); async function checkTargetText() { // 初始化Chrome浏览器驱动 const driver = await new Builder() .forBrowser('chrome') .setChromeOptions(new chrome.Options()) .build(); try { // 打开目标网站 await driver.get('http://WEBSITE'); // 获取页面源码,检查指定文本是否存在 const pageSource = await driver.getPageSource(); if (!pageSource.includes('TEXT')) { throw new Error('指定文本没在页面里找到哦'); } console.log('太棒了,指定文本存在!'); } catch (err) { console.error(err.message); } finally { // 用完记得关闭浏览器 await driver.quit(); } } // 调用执行函数 checkTargetText();
这段代码和你Python版本的逻辑完全一致:启动浏览器、打开页面、获取源码、检查文本,用JS的includes()方法替代了Python里的in操作符。
二、纯浏览器端JS实现(直接在控制台/前端代码用)
如果你不需要用Selenium,只是想在浏览器里直接检查页面文本,也可以用这两种方法:
// 方法1:检查页面所有可见+不可见的文本内容 const fullPageText = document.body.textContent; const hasText = fullPageText.includes('TEXT'); console.log(hasText ? '文本存在~' : '没找到指定文本'); // 方法2:检查页面的完整HTML源码(和Selenium的page_source逻辑一样) const pageSource = document.documentElement.outerHTML; const hasTextInSource = pageSource.includes('TEXT'); console.log(hasTextInSource ? '文本在源码里存在' : '源码里没找到指定文本');
小贴士: textContent会获取所有元素的文本(包括隐藏元素),如果只想检查可见文本,可以换成document.body.innerText。
内容的提问来源于stack exchange,提问作者DenisPavlichenko




