硒:由于线程错误,无法滚动单击不可见的元素:元素不可见

时间:2019-08-11 01:45:49

标签: java selenium selenium-webdriver xpath webdriverwait

我试图单击一个不可见的元素,需要向下滚动才能看到。为了解决这个问题,我尝试使用javascript执行程序和动作,但是它们不起作用,因为即使在滚动之前,我还是收到一个线程错误,指出该元素不可见。我已确保该元素的xpath正确,并验证了代码可用于无需滚动即可看到的元素。

<div class="product-grid-item clearfix" data-alpha="LOG ON T-SHIRT BLACK" data-price="4800" data-i="27">

 <a href="/products/8r9ya45zmdwz" class="product-link">

<img src="[//cdn.shopify.com/s/files/1/0923/4190/products/Palace-2019-Autumn-T-Shirt-Log-On-black-1336\_200x200\_crop\_center@2x.jpg?v=1565334138](//cdn.shopify.com/s/files/1/0923/4190/products/Palace-2019-Autumn-T-Shirt-Log-On-black-1336_200x200_crop_center@2x.jpg?v=1565334138)" alt="LOG ON T-SHIRT BLACK" class="img">

  </a>

 <div class="product-info">

<a href="/products/8r9ya45zmdwz" class="product-link">

<h3 class="title">LOG ON T-SHIRT BLACK</h3>

</a>

<div class="price">

<span class="prod-price">$48</span>
</div>

  </div>

</div>

我尝试了javascript执行程序和操作

WebElement element = driver.findElement(By.xpath("//*[@data-alpha='" + productName + "' and @class='product-grid-item clearfix']")); //error occurs at this line

int elementPosition = element.getLocation().getY();
String js = String.format("window.scroll(0, %s)", elementPosition);
((JavascriptExecutor)driver).executeScript(js);
element.click();

WebElement element = driver.findElement(By.xpath("//*[@data-alpha='" + productName + "' and @class='product-grid-item clearfix']")); //error occurs at this line
Actions builder = new Actions(driver);
builder.moveToElement(element);
builder.click();
builder.build().perform();

错误消息:

no such element: Unable to locate element: {"method":"xpath","selector":"//*[@data-alpha='WINDOWLICKER HOOD GREY MARL' and @class='product-grid-item clearfix']"}

2 个答案:

答案 0 :(得分:1)

尝试使用WebDriverWait并用contains更改定位符,可能包含空格。

WebDriverWait wait = new WebDriverWait(driver, 60);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[contains(@data-alpha,'" + productName.trim() + "') and @class='product-grid-item clearfix']")));

scroll here....

答案 1 :(得分:-1)

该元素似乎是一个 dynamic 元素,正如您所提到的,元素不可见,需要向下滚动才能显示,因此您可以使用以下解决方案:

  • 使用 WebDriverWait ExpectedConditions elementToBeClickable()

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='product-grid-item clearfix' and contains(@data-alpha, 'LOG ON T-SHIRT BLACK')]//a[@class='product-link' and contains(@href, 'products')]/img[contains(@src, 'shopify')]"))).click();
    
  • 通过操作使用 WebDriverWait ExpectedConditions elementToBeClickable()

    new Actions(driver).moveToElement(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='product-grid-item clearfix' and contains(@data-alpha, 'LOG ON T-SHIRT BLACK')]//a[@class='product-link' and contains(@href, 'products')]/img[contains(@src, 'shopify')]")))).click().build().perform();
    
相关问题