我有这段代码,但失败,并显示错误NoSuchElementException: Message: Unable to locate element: //span[contains(text(), 'Distance')]
。
这是我用来抓取的page。对于我的输入数据,distance
应该等于:
261.30(NM)/ 300.76(MI)/ 483.93(KM)
我的代码有什么问题?我检查了是否正确指定了所有元素。
import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.options import Options
options = Options()
options.headless = True
browser = webdriver.Firefox(options=options)
browser.get("https://www.flightmanager.com/content/timedistanceform.aspx")
departure_airport = browser.find_element_by_id("ContentPlaceHolder1_txtDepartureICAO")
arrival_airport = browser.find_element_by_id("ContentPlaceHolder1_txtArrivalICAO")
submit = browser.find_element_by_id("ContentPlaceHolder1_BtnSubmit")
departure_airport.send_keys("LEMD")
arrival_airport.send_keys("LEBL")
submit.click()
delay = 3 # seconds
try:
WebDriverWait(browser, delay)
distance = browser.find_element_by_xpath("//span[contains(text(), 'Distance')]").text
print(distance)
time.sleep(10)
except NoSuchElementException:
print("Scraping failed")
time.sleep(10)
browser.quit()
答案 0 :(得分:1)
您收到NoSuchElementException
错误,因为您的xpath没有指向任何内容。
那
distance = browser.find_element_by_xpath(
"//*[contains(text(), 'Distance')]/span[1]"
).text