我對硒進行了測驗:
@Test
public void Test(){
open("https://market.yandex.ru/catalog--smartfony/54726/list?hid=91491&glfilter=7893318:153043&glfilter=4940921:13475069&onstock=1&local-offers-first=0");
new AfterPhonesCategory()
.collectResults();
}
我有一個獲取產品名稱并回傳硒元素的方法,當產品用完時,我們轉到下一頁并再次獲取元素,直到它們用完:
public class AfterPhonesCategory {
public List<String> collectResultsFromPage() {
List<SelenideElement> resultsNameWebElement = $$x("//article//h3[@data-zone-name = 'title']//span");
Assertions.assertTrue(resultsNameWebElement.stream().anyMatch(x->x.getText().contains("Apple")),
"the snippet does not contain the name of the apple");
return resultsNameWebElement.stream() //line 34
.map(SelenideElement::getText)
.collect(Collectors.toList());
}
private boolean initNextPageButton() {
List<SelenideElement> goNextPageButton = $$x("//a[contains(@class, '_3OFYT')]");
if(goNextPageButton.size() > 0){
goNextPageButton.get(0).click();
return true;
}
else
return false;
}
private List<String> findResults;
public AfterPhonesCategory collectResults() {
findResults = collectResultsFromPage();
while (initNextPageButton()) { //line 52
findResults.addAll(collectResultsFromPage());
}
return this;
}
但是在執行代碼時出現錯誤:
Caused by: org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
at pages.AfterPhonesCategory.collectResultsFromPage(AfterPhonesCategory.java:34)
at pages.AfterPhonesCategory.collectResults(AfterPhonesCategory.java:52)
我究竟做錯了什么?
uj5u.com熱心網友回復:
StaleElementReferenceException 僅當您的元素在您的網站中不存在(消失或未構造直到)時才會發生。請添加等待條件以檢查元素的可見性。
By optionXpath = By.xpath("your xpath fp goes here !");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(optionXpath));
wait.until(ExpectedConditions.visibilityOfElementLocated(optionXpath));
driver.findElement(optionXpath).click();
在未構造的情況下:
您需要添加等待條件
在消失的情況下:
您對元素的操作是錯誤的。在您的失敗代碼之前添加螢屏截圖并重新檢查您的代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/311626.html
上一篇:無法獲取元素的大小和硒中的類
