【问题标题】:Selenium is unable to find element with data-testid attributeSelenium 无法找到具有 data-testid 属性的元素
【发布时间】:2020-05-31 20:00:22
【问题描述】:

试图找到下面的元素尝试了以下没有任何工作可以帮助任何人。

<button data-testid="addToClientBasket" 
        class="sc-kfGgVZ kcCRfu">
    <span><i class="icon-Expand_Cross_30_by_30"></i>Add To Basket</span>
</button>
By.xpath("//button[@data-testid='addToClientBasket'");

By.xpath("//div[@id='root']/div/div/div/div[4]/div/div/div[2]/button/span";

By.cssSelector("button.sc-kfGgVZ.kcCRfu.added");

By.cssSelector("button.sc-kfGgVZ.kcCR");

By.cssSelector("button[class='sc-kfGgVZ kcCRfu']");

【问题讨论】:

  • 我要找的元素在下面。
  • 你试过按类名选择它吗?
  • 你能给我们链接到有这个网页元素的网站吗?

标签: java selenium-webdriver xpath css-selectors webdriverwait


【解决方案1】:

试试下面的定位器

button.sc-kfGgVZ.kcCRfu
button[data-testid="addToClientBasket"]

//button[@class='sc-kfGgVZ kcCRfu']
//button[@data-testid="addToClientBasket"]

定位器在您的情况下不起作用的原因

By.xpath("//button[@data-testid='addToClientBasket'");

属性值后没有右括号

By.xpath("//div[@id='root']/div/div/div/div[4]/div/div/div[2]/button/span";

不确定你的元素路径是否正确

By.cssSelector("button.sc-kfGgVZ.kcCRfu.added");

没有added类名的按钮

By.cssSelector("button.sc-kfGgVZ.kcCR");

没有指定类组合的按钮

By.cssSelector("button[class='sc-kfGgVZ kcCRfu']");

这些是 2 个类,因此您必须将空白替换为 .

【讨论】:

    【解决方案2】:

    要使用Selenium 将带有文本的元素标识为添加到篮子,您可以使用以下任一Locator Strategies

    • cssSelector

      driver.findElement(By.cssSelector("button[data-testid='addToClientBasket']>span>i.icon-Expand_Cross_30_by_30"));
      
    • xpath

      driver.findElement(By.xpath("//button[@data-testid='addToClientBasket']/span[contains(., 'Add To Basket')]"));
      

    据推测,继续前进,您将在元素上调用 click(),在这种情况下,理想情况下,您需要为 elementToBeClickable() 诱导 WebDriverWait,您可以使用以下任一 Locator Strategies

    • cssSelector:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[data-testid='addToClientBasket']>span>i.icon-Expand_Cross_30_by_30"))).click();
      
    • xpath:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@data-testid='addToClientBasket']/span[contains(., 'Add To Basket')]"))).click();
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 2022-07-28
      • 1970-01-01
      • 2013-07-03
      • 2015-03-06
      • 1970-01-01
      • 2015-02-03
      相关资源
      最近更新 更多