Python Selenium:陈旧元素引用异常错误

时间:2017-10-20 05:26:38

标签: python loops selenium webdriver

我面临的问题在于这些循环的迭代,一旦从网页下载第一个文件,我收到错误:

“selenium.common.exceptions.StaleElementReferenceException:消息:陈旧元素引用:元素不再附加到DOM或页面已刷新”

“97081 data-extension xml”是迭代中的第二个可下载文件。我特此附上代码,任何纠正这一点的建议都将不胜感激。

import os
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

fp = webdriver.FirefoxProfile()

fp.set_preference("browser.download.folderList", 2)
fp.set_preference("browser.download.manager.showWhenStarting", False)
fp.set_preference("browser.download.dir", "F:\Projects\Poli_Map\DatG_Py_Dat")
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/xml")

driver = webdriver.Firefox(firefox_profile=fp)

driver.get('https://data.gov.in/catalog/variety-wise-daily-market-prices-data-cauliflower')
wait = WebDriverWait(driver, 10)

allelements = driver.find_elements_by_xpath("//a[text()='xml']")

for element in allelements:
    element.click()
    class FormPage(object):
        def fill_form(self, data):
            driver.execute_script("document.getElementById('edit-download-reasons-non-commercial').click()")
            driver.execute_script("document.getElementById('edit-reasons-d-rd').click()")
            driver.find_element_by_xpath('//input[@name = "name_d"]').send_keys(data['name_d'])
            driver.find_element_by_xpath('//input[@name = "mail_d"]').send_keys(data['mail_d'])
            return self

        def submit(self):
            driver.execute_script("document.getElementById('edit-submit').click()")

    data = {
        'name_d': 'xyz',
        'mail_d': 'xyz@outlook.com',
    }
    time.sleep(5)
    FormPage().fill_form(data).submit()

    time.sleep(5)
    window_before = driver.window_handles[0]
    driver.switch_to_window(window_before)
    driver.back()

2 个答案:

答案 0 :(得分:3)

在您致电submit() allelements内的网页元素后,页面刷新后不再有效

而不是

allelements = driver.find_elements_by_xpath("//a[text()='xml']")

for element in allelements:
    element.click()

allelements = len(driver.find_elements_by_xpath("//a[text()='xml']"))

for index in range(allelements):
    driver.find_elements_by_xpath("//a[text()='xml']")[index].click()

答案 1 :(得分:0)

>>>Customize the for loop as:  

from selenium.common import exceptions  

and customize your code of for loop as:  

for element in allelements:
   try:  
     //your code to find element and operations with that element
   except exceptions.StaleElementReferenceException:  
        pass