【发布时间】:2018-07-09 15:23:22
【问题描述】:
我正在尝试从一个名为 Correios 的网站获取所有数据,在这个网站上,我需要处理一些下拉列表,我遇到了一些问题,例如:它没有从第一个 Dropbox 信息中获取所有值。
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.select import Select
chrome_path = r"C:\\Users\\Gustavo\\Desktop\\geckodriver\\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
lista_x = []
driver.get("http://www2.correios.com.br/sistemas/agencias/")
driver.maximize_window()
estado_select = Select(driver.find_element_by_id('estadoAgencia'))
WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, 'municipioAgencia')))
municipio_select = Select(driver.find_element_by_id('municipioAgencia'))
for opt in estado_select.options:
print(opt.get_attribute('innerHTML'))
opt.click()
for opt2 in municipio_select.options:
print(opt.get_attribute('innerHTML'))
opt2.click()
driver.close()
有时我的代码运行正常,但有时它会给我这个错误:
ACRE
ACRE
ALAGOAS
ALAGOAS
Traceback (most recent call last):
File "C:\Users\Gustavo\Desktop\insper\trabalho\Correios3.py", line 23, in <module>
opt2.click()
File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
self._execute(Command.CLICK_ELEMENT)
File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 628, in _execute
return self._parent.execute(command, params)
File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute
self.error_handler.check_response(response)
File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=67.0.3396.99)
(Driver info: chromedriver=2.40.565498 (ea082db3280dd6843ebfb08a625e3eb905c4f5ab),platform=Windows NT 10.0.17134 x86_64)
我该怎么办?
【问题讨论】:
-
还是出现同样的错误,我要放新代码