[英]Stale element reference: element is not attached to the page document when looping through pages
[英]Getting an “Stale element reference” When trying to loop through pages with the intention of scraping multiple pages
我的 Python 代碼有問題。 目的是用Selenium打開網站(craigslist),搜索一個文本(Honda),然后抓取這個網站的三個頁面。 我不斷得到
“StaleElementReferenceException:過時的元素引用:元素未附加到頁面文檔”異常
當迭代到達第二頁時。 我無法確切說明為什么它停在第二頁而不是再次單擊“下一步”按鈕到達第三頁,然后最終抓取數據並打印出來。
這是我的代碼:
import time
from selenium import webdriver
from bs4 import BeautifulSoup
DRIVER_PATH = "/Users/mouradsal/Downloads/DataSets Python/chromedriver"
URL = "https://vancouver.craigslist.org/"
browser = webdriver.Chrome(DRIVER_PATH)
browser.get(URL)
browser.maximize_window()
time.sleep(4)
search = browser.find_element_by_css_selector("#query")
search.send_keys("Honda")
search.send_keys(u'\ue007')
content = browser.find_elements_by_css_selector(".hdrlnk")
button = browser.find_element_by_css_selector(".next")
for i in range(0,3):
button.click()
print("Count: "+ str(i))
time.sleep(10)
print("done loop ")
for e in content:
start = e.get_attribute("innerHTML")
soup = BeautifulSoup(start, features=("lxml"))
print(soup.get_text())
print("***************************")
任何建議將不勝感激!
謝謝
for i in range(0,3):
button = driver.find_element_by_css_selector(".next")
button.click()
print("Count: "+ str(i))
time.sleep(10)
您需要嵌套您發現的元素,導致每次訪問新頁面時 webelement 都會發生變化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.