我最近开始学习自动化。我正在尝试自动化Finnair.com网站。 但在我的代码中出现了以下问题。在点击 "Helsinki "项目之前,它都能正常工作。
错误。
check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document Traceback (most recent call last): line 35, in <module> if city.text == "Helsinki (HEL)": line 76, in text return self._execute(Command.GET_ELEMENT_TEXT)['value'] Python37\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute return self._parent.execute(command, params) line 321, in execute self.error_handler.check_response(response) 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=81.0.4044.138)--- Error
我的代码
driver.get("https://www.finnair.com/us-en")
time.sleep(5)
driver.find_element_by_xpath("//button[contains(@class,'btn rounded pr-large-x tr-small')]").click()
time.sleep(5)
wait = WebDriverWait(driver,10)
traveltype = driver.find_elements_by_css_selector("span.mr-xxsmall-l")
traveltype[1].click() #Oneway according to the index to change i can say 0
print(len(traveltype))
#Selecting Orgin and Destination Locations
driver.find_element_by_class_name("bw-origin").click()
time.sleep(5)
driver.find_element_by_css_selector("#origin-input").send_keys("HEL")
time.sleep(5)
#driver.find_element_by_xpath("//div[text()='Helsinki (HEL)']").click()
orgin = driver.find_elements_by_css_selector("div.ts-xsmall")
time.sleep(5)
for city in orgin:
if city.text == "Helsinki (HEL)":
city.click()
time.sleep(5)
driver.find_element_by_xpath("//div[contains(@class,'bw-destination')]").click()
driver.find_element_by_xpath("//input[contains(@placeholder,'Type and select destination')]").send_keys("TLL")
driver.find_element_by_xpath("//div[text()='Tallinn (TLL)']").click()
只要添加一个 break
在你点击该元素后,就会出现 "bw-origin"。一旦你找到并点击了匹配,原点列表("bw-origin")就不存在了。这就是导致 StaleElementReferenceException
. 同时也不需要在找到匹配项后循环浏览整个列表。
for city in orgin:
if city.text == "Helsinki (HEL)":
city.click()
break
附注 - 考虑使用更多的 WebDriverWait
s和少 time.sleep
.