【问题标题】:Message: stale element reference: element is not attached to the page document while clicking on multiple links on the webpage using Selenium Python消息:过时的元素引用:使用 Selenium Python 单击网页上的多个链接时,元素未附加到页面文档
【发布时间】:2020-11-06 14:09:15
【问题描述】:

我正在尝试单击此 page 上所有可能的课程链接,但它给了我这个错误:

Message: stale element reference: element is not attached to the page document

这是我的代码:

driver = webdriver.Chrome()
driver.get('https://catalog.maryville.edu/preview_program.php?catoid=18&poid=3085&_ga=2.22513656.232086776.1594848572-196623372.1594848572')
driver.implicitly_wait(10)
links = driver.find_elements_by_xpath('//*[@id="table_block_n2_and_content_wrapper"]/table/tbody/tr[2]/td[1]/table/tbody/tr/td/table/tbody/tr[2]/td/div/div/ul/li/span/a')

for link in links:
    driver.execute_script("arguments[0].click();", link)
    time.sleep(3)
driver.quit()

知道如何解决这个问题吗?

【问题讨论】:

    标签: python-3.x selenium xpath css-selectors staleelementreferenceexception


    【解决方案1】:

    要点击页面https://catalog.maryville.edu/preview_program.php?catoid=18&poid=3085&_ga=2.22513656.232086776.1594848572-196623372.1594848572上的所有课程链接,您可以使用以下任一Locator Strategies

    • 使用CSS_SELECTOR

      driver.get("https://catalog.maryville.edu/preview_program.php?catoid=18&poid=3085&_ga=2.22513656.232086776.1594848572-196623372.1594848572")
      links = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.acalog-course>span>a")))
      for link in links:
          link.click()
          time.sleep(3)
      driver.quit()
      
    • 使用XPATH

      driver.get("https://catalog.maryville.edu/preview_program.php?catoid=18&poid=3085&_ga=2.22513656.232086776.1594848572-196623372.1594848572")
      links = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//li[@class='acalog-course']/span/a")))
      for link in links:
          link.click()
          time.sleep(3)
      driver.quit()
      
    • 注意:您必须添加以下导入:

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      

    参考

    您可以在StaleElementReferenceException找到相关的详细讨论:

    【讨论】:

    • 您好,感谢您的解决方案。我尝试了您的代码,但它跳过了一些链接并且出现错误:消息:元素点击被拦截:元素 在点 (181, 528) 处不可点击。其他元素会收到点击:
      ...
    • @Jasmine 我想这个答案解决了你最初的 stale element reference 问题
    猜你喜欢
    • 2022-08-17
    • 2022-01-21
    • 2020-11-13
    • 2020-10-30
    • 2018-10-23
    • 1970-01-01
    • 2019-09-30
    • 2021-12-15
    • 2019-02-03
    相关资源
    最近更新 更多