我正在尝试循环遍历与 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/