【问题标题】:Unable to find element in Selenium Chrome (JavaScript)无法在 Selenium Chrome (JavaScript) 中找到元素
【发布时间】:2022-08-14 05:57:25
【问题描述】:

我正在使用带有 selenium 的 JavaScript 来自动化一个网页,该网页有几个我需要点击的按钮。我的代码首先连接到现有的 chrome 窗口,如下所示:

var chrome = require(\"selenium-webdriver/chrome\");
    var options = new chrome.Options();
    options.options_[\"debuggerAddress\"] = \"127.0.0.1:9222\";
    var driver = new webdriver.Builder()
        .forBrowser(\'chrome\')
        .setChromeOptions(options)
        .build();

驱动程序成功运行并具有正确的页面,我通过让驱动程序打印页面的源代码来验证这一点,该源代码与右键菜单中的站点的页面源相匹配。

我还有一个名为 checkForName() 的函数,给定一个 XPath,它返回元素供 selenium 交互

async function checkForName(selector) {
  console.log(\"Checking for name\");
  try {
            const element = await driver.findElement(By.xpath(selector));
            return element;
  } finally {
            console.log(\"Error: element \" + selector + \" not found\");
            return false;
  }
}

然后稍后在程序中调用此函数

element = await checkForName(\"//button[@class=\'mBiMV\']\");
if(element) {
   element.click();
}

但是,当程序运行时,控制台中会弹出此错误:

Checking for name
SnapBot-JS.js:18
Error: label //button[@class=\'mBiMV\'] not found

我已验证该按钮存在,并且文档在 chromedriver 连接之前已完全加载,所以我不确定此时该做什么

编辑: 这是相关按钮的 HTML 代码:

<button type=\"button\" class=\"mBiMV\">
  • 我怀疑会解决您的问题的是使用等待,类似于`await driver.wait(until.elementLocated(By.id(\'foo\')), 30000);`。可以在selenium.dev/documentation/webdriver/waits 找到有关此文档的 Selenium 文档
  • 我将 try 块中的代码更改为此,但它立即引发相同的错误。 const element = await driver.wait(until.elementLocated(By.xpath(selector)), 30000); return element;
  • 我建议切换到会自动等待的剧作家。它对初学者来说更加简单(尤其是对于 javascript)

标签: javascript selenium google-chrome selenium-chromedriver


【解决方案1】:

班级名称mBiMV 是动态生成的,并且迟早会发生变化。它们可能会在您下次重新访问应用程序时甚至在下一次应用程序启动时发生变化。所以不能用于定位器。相反,您需要使用具有静态值的属性。


解决方案

根据 HTML:

<button type="button" class="mBiMV">

似乎没有提供静态值的其他属性type="button"作为一个属性太笼统了。在这些情况下,您可能希望移动到父元素并使用静态属性来识别它的后代&lt;button&gt;独一无二。举个例子:

<div class="foo" id="bar">
    <button type="button" class="mBiMV">
    

上述 HTML 的有效 locator strategy 将是以下任一:

  • 使用css

    const element = await driver.findElement(By.css("div.foo#bar > button"));
    
  • 使用路径

    const element = await driver.findElement(By.xpath("//div[@class='foo' and @id='bar']/button"));
    

【讨论】:

    猜你喜欢
    • 2022-09-30
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 2018-08-01
    • 2018-01-10
    • 2023-04-01
    相关资源
    最近更新 更多