python - 循环元素时如何解决 StaleElementReferenceException (Selenium)

标签 python selenium for-loop selenium-chromedriver staleelementreferenceexception

我正在尝试抓取一个网站以获取有关足球比赛的信息。因此我在 Python 中使用 Selenium 库。

我将所有所需匹配项中的可点击 html 元素存储在名为“completed_matches”的列表中。我创建了一个 for 循环,它迭代所有这些可点击的 html 元素。在循环内,我单击当前的 html 元素并打印新的 URL。代码如下所示:

from selenium import webdriver
import selenium
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome(r"C:\Users\Mart\Downloads\chromedriver_win32_2\chromedriver.exe")
url = "https://footystats.org/spain/la-liga/matches"
driver.get(url)
completed_matches = driver.find_elements_by_xpath("""//*[@id="matches-list"]/div[@class='full-matches-table mt2e ' or @class='full-matches-table mt1e ']/div/div[2]/table[@class='matches-table inactive-matches']/tbody/tr[*]/td[3]/a[1]/span""");
print(len(completed_matches))
for match in completed_matches:
        match.click()
        print("Current driver URL: " + driver.current_url)

输出如下所示:

159
Current driver URL: https://footystats.org/spain/fc-barcelona-vs-real-club-deportivo-mallorca-h2h-stats#632514
---------------------------------------------------------------------------
StaleElementReferenceException            Traceback (most recent call last)
<ipython-input-3-da5851d767a8> in <module>
      4 print(len(completed_matches))
      5 for match in completed_matches:
----> 6         match.click()
      7         print("Current driver URL: " + driver.current_url)

~\Anaconda3\lib\site-packages\selenium\webdriver\remote\webelement.py in click(self)
     78     def click(self):
     79         """Clicks the element."""
---> 80         self._execute(Command.CLICK_ELEMENT)
     81 
     82     def submit(self):

~\Anaconda3\lib\site-packages\selenium\webdriver\remote\webelement.py in _execute(self, command, params)
    631             params = {}
    632         params['id'] = self._id
--> 633         return self._parent.execute(command, params)
    634 
    635     def find_element(self, by=By.ID, value=None):

~\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py in execute(self, driver_command, params)
    319         response = self.command_executor.execute(driver_command, params)
    320         if response:
--> 321             self.error_handler.check_response(response)
    322             response['value'] = self._unwrap_value(
    323                 response.get('value', None))

~\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py in check_response(self, response)
    240                 alert_text = value['alert'].get('text')
    241             raise exception_class(message, screen, stacktrace, alert_text)
--> 242         raise exception_class(message, screen, stacktrace)
    243 
    244     def _value_or_default(self, obj, key, default):

StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=79.0.3945.79)
  (Driver info: chromedriver=72.0.3626.7 (efcef9a3ecda02b2132af215116a03852d08b9cb),platform=Windows NT 10.0.18362 x86_64)

completed_matches列表包含159个html元素,但for循环只显示第一个点击的链接,然后抛出StaleElementReferenceException...

有谁知道这个问题怎么解决吗?

最佳答案

您要查找的网址位于您单击的链接中。您选择单击的父元素。 StaleElementReferenceException 是因为单击链接后,页面会更改,在单击的第一个元素之后的所有元素均已过时。

from selenium import webdriver
import selenium
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome(r"C:\Users\Mart\Downloads\chromedriver_win32_2\chromedriver.exe")
url = "https://footystats.org/spain/la-liga/matches"
driver.get(url)
completed_matches = driver.find_elements_by_xpath("""//*[@id="matches-list"]/div[@class='full-matches-table mt2e ' or @class='full-matches-table mt1e ']/div/div[2]/table[@class='matches-table inactive-matches']/tbody/tr[*]/td[3]/a[1]/span""");
print(len(completed_matches))
for match in completed_matches:
        #match.click()
        #print("Current driver URL: " + driver.current_url)
        match_parent = match.find_element_by_xpath("..")
        href = match_parent.get_attribute("href")
        print("href: ", href)

关于python - 循环元素时如何解决 StaleElementReferenceException (Selenium),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59325073/

相关文章:

python - Pandas groupby : treat two columns as one

javascript - 在python中填写表单并按下javascript按钮

java - 在 Java 中将数组中特定点周围的值相加

python - 为什么 vars(response) 不显示response.text? (使用Python请求模块)

python - pygame.time.set_timer 困惑?

python - 使用 Flask-WTForms,如何设置 html 表单部分的样式?

javascript - Webdriver.io 元素使用

python - 如何解决 selenium webdriver 中的斜线问题?

Python: "if i.find(' a') ['id' ] is not None :"returns TypeError ' NoneType' 对象不可下标,但 print() 返回一个值

java - 减慢 Java For 循环中对象的移动速度