首页 > 解决方案 > 处理几页硒脚本后出现NoSuchElementException错误

问题描述

我想知道是否有任何方法可以保护脚本在由于 NoSuchElementException 错误而退出之前不被破坏。我的脚本适用于网站上的前几页,并且能够找到元素,但在前几页之后,由于没有此类元素错误,它退出了。我想知道如何防止程序退出并一直到页面末尾。抱歉,我是堆栈溢出的新手,所以如果我问得正确,我不会。谢谢!


line 39, in <module>
    main3 = main.find_element_by_xpath('//*[@id="main-content-column"]/div/div[7]/div/div[2]/div/div/ng-transclude/table/tbody')


 raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="main-content-column"]/div/div[7]/div/div[2]/div/div/ng-transclude/table/tbody"}
  


标签: pythonseleniumweb-scraping

解决方案


并非所有元素都具有相同的 Xpath 或 Css。尝试查看它何时失败 - 也许该元素有另一个表达式。

另外,尝试使用这个:

WebDriverWait wait = new WebDriverWait(browser, secondsToWait); 
wait.until(ExpectedConditions.presenceOfElementLocated(By.id(elementID)));

有许多 ExpectedConditions,如 elementToBeClickable、elementToBeVissible 等。


推荐阅读