Java 硒:Can';t滚动以单击由于线程错误而不可见的元素:元素不可见
我试图单击一个不可见的元素,需要向下滚动才能看到它。为了解决这个问题,我尝试使用javascript executor和action,但它们不起作用,因为在滚动之前,我收到一个线程错误,说元素不可见。我已经确保元素的xpath是正确的,并验证了代码是否可以使用无需滚动即可看到的元素Java 硒:Can';t滚动以单击由于线程错误而不可见的元素:元素不可见,java,selenium,selenium-webdriver,xpath,webdriverwait,Java,Selenium,Selenium Webdriver,Xpath,Webdriverwait,我试图单击一个不可见的元素,需要向下滚动才能看到它。为了解决这个问题,我尝试使用javascript executor和action,但它们不起作用,因为在滚动之前,我收到一个线程错误,说元素不可见。我已经确保元素的xpath是正确的,并验证了代码是否可以使用无需滚动即可看到的元素 <div class="product-grid-item clearfix" data-alpha="LOG ON T-SHIRT BLACK" data-price="4800" data-i="27"&g
<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>
及
错误消息:
no such element: Unable to locate element: {"method":"xpath","selector":"//*[@data-alpha='WINDOWLICKER HOOD GREY MARL' and @class='product-grid-item clearfix']"}
尝试使用
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....
该元素似乎是一个动态元素,正如您所提到的,该元素不可见,需要向下滚动才能可见,以便您可以使用以下任一解决方案:
- 使用WebDriverWait和ExpectedConditions以及
:ElementToBickable()
- 通过操作使用WebDriverWait和ExpectedConditions以及
:ElementToBickable()
WebDriverWait
确保元素存在,然后执行滚动。
no such element: Unable to locate element: {"method":"xpath","selector":"//*[@data-alpha='WINDOWLICKER HOOD GREY MARL' and @class='product-grid-item clearfix']"}
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....
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();
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();