Python Selenium StaleElementReferenceException

时间:2018-04-04 18:18:52

标签: python google-chrome selenium webdriver

我已经在其他帖子上看到过这方面的解决方案(主要是建议更长的等待时间),但是已经尝试过并且没有取得成功。

这是我得到的错误:

Traceback (most recent call last):
  File "LobbyistsPrep.py", line 126, in <module>
    the_download = get_file(year, report, download_dir)
  File "LobbyistsPrep.py", line 28, in get_file
    Year.select_by_visible_text(year_text)
  File "C:\Python27\lib\site-packages\selenium\webdriver\support\select.py", lin
e 120, in select_by_visible_text
    self._setSelected(opt)
  File "C:\Python27\lib\site-packages\selenium\webdriver\support\select.py", lin
e 212, in _setSelected
    option.click()
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py",
line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py",
line 501, in _execute
    return self._parent.execute(command, params)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 308, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py"
, line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale elemen
t reference: element is not attached to the page document
  (Session info: chrome=65.0.3325.181)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d902
3f),platform=Windows NT 6.1.7601 SP1 x86_64)

以下是相关代码:

def get_file(year_text, category, download_dir):
    # Store a list of files in the Downloads directory.
    # We will use this later to determine the filename of the the CSV we downloaded.
    downloads_before = os.listdir( download_dir )

    # Change the Year dropdown
    Year = Select(driver.find_element_by_name('ctl00$ctl00$ContentPlaceHolder$ContentPlaceHolder1$ddYear'))
    Year.select_by_visible_text(year_text)
    time.sleep(30)

    # Change the Expenditure Type dropdown
    Type = Select(driver.find_element_by_name('ctl00$ctl00$ContentPlaceHolder$ContentPlaceHolder1$ddExpType'))
    Type.select_by_visible_text(category)
    time.sleep(30)

    # Change the Report Month dropdown
    Month = Select(driver.find_element_by_name('ctl00$ctl00$ContentPlaceHolder$ContentPlaceHolder1$ddMonth'))
    Month.select_by_visible_text('-- All Available --')
    time.sleep(30)

    # Click the Export to CSV button (downloads the CSV file)
    driver.find_element_by_name('ctl00$ctl00$ContentPlaceHolder$ContentPlaceHolder1$btnExport').click()
    time.sleep(30)

    # Now that we have downloaded the file, lets check the Downloads directory again and compare.
    downloads_after = os.listdir( download_dir )
    downloads_change = set(downloads_after) - set(downloads_before)
    # If there is only one difference, then that file is the one we downloaded.
    if len(downloads_change) == 1:
        file_name = downloads_change.pop()
        file_path = download_dir + file_name
        return file_path
    # Otherwise, something went wrong: Either the number of files changed by MORE than one, or NOTHING was downloaded.
    else:
        return False

driver.get('http://mec.mo.gov/mec/Lobbying/Lob_ExpCSV.aspx')
time.sleep(30)

for report in reports_wanted:
    for year in years_wanted:
        the_download = get_file(year, report, download_dir)
        if the_download:
            if report == 'Group':
                print 'Downloaded ' + the_download + '. Adding to GROUP.  Report:\t' + year + '\t' + report
                group_files.append(the_download)
            else:
                print 'Downloaded ' + the_download + '. Adding to INDIV.  Report:\t' + year + '\t' + report
                files.append(the_download)
        else:
            print 'PROBLEM DOWNLOADING: \t' + year + '\t' + report

我们的time.sleep曾经是time.sleep(2) - 我已经尝试将它改为30,但这也无济于事。

我仍然很擅长去除刮刀,而这个刮刀并非由我制造,所以请保持温和。提前致谢。

2 个答案:

答案 0 :(得分:0)

将修正问题的评论转换为其他人的答案。

最终解决上述问题的原因是将 Chromedriver 更新为至少2.36,因为它们在Chrome build 65上运行,而当前版本不支持Chromedriver 2.33https://sites.google.com/a/chromium.org/chromedriver/downloads

通过保持这些更新或推荐配对,您将遇到更少的问题,如chromedriver下载登录页面所述。

如果您正在寻找StaleElementReferenceException

的帮助

以下是 wiki 的定义:

  

当对元素的引用现在“陈旧”时抛出。

     

陈旧意味着该元素不再出现在页面的DOM上。

     

StaleElementReferenceException的可能原因包括但不包括   限于:

     

您不再在同一页面上,或者页面可能有   自元素定位以来刷新。

     

该元素可能已经存在   删除并重新添加到屏幕,因为它被找到了。如一个   元素被重新安置。这通常可以通过javascript实现   更新值并重建节点时的框架。

     

元素可以   已经在iframe或其他已刷新的上下文中。

请参阅以下内容:

答案 1 :(得分:0)

我在java中只有一个解决方案,但它有效。

如果抛出异常,我会抓住它并重试:

boolean isElementFound = false;

while(!isElementFound){

  try{

     WebElement myElement = Driver.findElement(By.id("elementID"));
     isElementFound = true;   

  }catch(StaleElementReferenceException e){
    //nothing!
  } 
}