python - Selenium - 为什么 NoSuchElementException 发生在第二次 for 循环迭代中?

标签 python selenium web-scraping nosuchelementexception

我正在尝试循环遍历与 div 标签匹配的 Web 元素列表。第一个循环运行顺利,但第二个循环抛出 NoSuchElementException。这是我的代码的最小示例:

for div in driver.find_elements_by_xpath("//div[@class='class_name']"):
    print(div.text)
    print(f"Current url 1: {driver.current_url}") # url 
    new_url = url + "/page/"
    time.sleep(2)
    driver.get(new_url)
    print(f"Current url 2: {driver.current_url}") # new_url
    time.sleep(2)
    # Then get info from the new url

    # Go back
    # driver.execute_script("window.history.go(-1)")
    driver.back()
    print(f"Current url 3: {driver.current_url}") # url
    print("Sleeping for 3 seconds from now...")
    time.sleep(3)

谢谢!

最佳答案

您收到 StaleElementReferenceException ,因为对您尝试使用的 Web 元素的引用不再有效,又称为陈旧。
请参阅here或有关过时元素引用异常的任何其他资源。
由于您访问了其他网页,即使您返回到初始网页,您在那里获得的所有 Web 元素也会变成陈旧元素。
要解决这个问题,您必须再次获取这些元素。
因此,我建议使用类似以下内容的代码,而不是当前的代码:

divs = driver.find_elements_by_xpath("//div[@class='class_name']")
for i in range(len(divs)):
    divs = driver.find_elements_by_xpath("//div[@class='class_name']")
    div = divs[i]
    print(div.text)
    print(f"Current url 1: {driver.current_url}") # url 
    new_url = url + "/page/"
    time.sleep(2)
    driver.get(new_url)
    print(f"Current url 2: {driver.current_url}") # new_url
    time.sleep(2)
    # Then get info from the new url

    # Go back
    # driver.execute_script("window.history.go(-1)")
    driver.back()
    print(f"Current url 3: {driver.current_url}") # url
    print("Sleeping for 3 seconds from now...")
    time.sleep(3)

您可以尝试按如下方式获取循环内的特定 div:

divs = driver.find_elements_by_xpath("//div[@class='class_name']")
for i in range(len(divs)):
    div = driver.find_element_by_xpath("(//div[@class='class_name'])[" + (str)i + "]")
    print(div.text)
    print(f"Current url 1: {driver.current_url}") # url 
    new_url = url + "/page/"
    time.sleep(2)
    driver.get(new_url)
    print(f"Current url 2: {driver.current_url}") # new_url
    time.sleep(2)
    # Then get info from the new url

    # Go back
    # driver.execute_script("window.history.go(-1)")
    driver.back()
    print(f"Current url 3: {driver.current_url}") # url
    print("Sleeping for 3 seconds from now...")
    time.sleep(3)

关于python - Selenium - 为什么 NoSuchElementException 发生在第二次 for 循环迭代中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69866701/

相关文章:

javascript - Promise.all, webdriver.promise.all, protractor.promise.all 的区别

python - 如何使用 selenium python 动态单击加载按钮?

python - 为什么 fillna 不能按预期模式工作

Python:从给定的数据集生成一个唯一的批处理

selenium - 使用 browsermob-proxy 的 Chrome 浏览器证书不是受信任的问题

Python Beautiful Soup 提取 HTML 元数据

python - 在 Pyside 中的自定义 QProgressBar 上绘制刻度

python - Selenium Python Ubuntu-导入http.client AttributeError

python - 我怎样才能抓取美国银行的营业时间?

javascript - 使用scrapy + splash返回html