我正在嘗試遍歷與 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)
謝謝!
uj5u.com熱心網友回復:
您得到的StaleElementReferenceException是因為對您嘗試使用的 Web 元素的參考不再有效,AKA 陳舊。
請參閱此處或有關 Stale Element Reference Exception 的任何其他資源。
由于您去了其他網頁,即使您回到初始網頁,您到達那里的所有網頁元素也會成為陳舊元素。
要克服這個問題,您必須再次獲取這些元素。
因此,我建議使用以下代碼代替您當前的代碼:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/351281.html
