【问题标题】:The element is not attached - Selenium in Python该元素未附加 - Python中的Selenium
【发布时间】:2025-12-11 16:30:01
【问题描述】:

我正在尝试通过在python 中使用selenium 从网站上的多个页面中抓取数据。该语法在第一页上运行并scrape 数据成功,但在第二页之后,它找不到点击按钮并停止抓取。我检查了网页的HTML codes,但第二页上的元素与第一页上的元素相同。我发现这个question 与同一问题有关。我认为问题是由于在更改DOM 后对按钮的引用丢失,但我仍然无法正确解决问题。我将不胜感激任何建议或解决方案。语法和结果如下:

browser = webdriver.Chrome(r"C:\Users\...\chromedriver.exe")
browser.get('https://fortune.com/global500/2019/walmart')

table = browser.find_element_by_css_selector('tbody')

data =[]

#Use For Loop for Index

i = 1
while True:
    if i > 5:
        break
    try:
        print("Scraping Page no. " + str(i))
        i = i + 1
        
        # Select rows in the table
        for row in table.find_elements_by_css_selector('tr'):
            cols = data.append([cell.text for cell in row.find_elements_by_css_selector('td')])

        try:
            WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH,'//span[@class="singlePagination__icon--2KbZn"]')))
            time.sleep(10)
        finally:
            browser.find_element_by_xpath('//span[@class="singlePagination__icon--2KbZn"]').click()
     
    except Exception as e:
        print(e)
        break


data1 = pd.DataFrame(data, columns=['Labels','Value'])

print(data1)

browser.close()

输出

Scraping Page no. 1
Scraping Page no. 2
Message: stale element reference: element is not attached to the page document
 (Session info: chrome=....)

                     Labels                    Value
0                      (...)                   (...)
1                      (...)                   (...)

【问题讨论】:

标签: python selenium selenium-webdriver web-scraping


【解决方案1】:

table = browser.find_element_by_css_selector('tbody') 行移动到您的while 循环中。这样您将在每个循环中获得对表格元素的最新引用,然后您应该不会看到任何过时的元素问题。

while True:
    table = browser.find_element_by_css_selector('tbody')
    if i > 5:

【讨论】: