Python NoSuchElementException:消息:无法定位元素://span[contains(text(),'Distance')]
我有这段代码,但它失败了,错误为NoSuchElementException:Message:无法定位元素://span[containstext,'Distance'] 这是我用来刮东西的。对于我的输入数据,距离应等于: 261.30牛米/300.76英里/483.93公里 我的代码有什么问题?我检查了所有元素的指定是否正确Python NoSuchElementException:消息:无法定位元素://span[contains(text(),'Distance')],python,selenium,selenium-webdriver,web-scraping,Python,Selenium,Selenium Webdriver,Web Scraping,我有这段代码,但它失败了,错误为NoSuchElementException:Message:无法定位元素://span[containstext,'Distance'] 这是我用来刮东西的。对于我的输入数据,距离应等于: 261.30牛米/300.76英里/483.93公里 我的代码有什么问题?我检查了所有元素的指定是否正确 import time from selenium import webdriver from selenium.webdriver.support.ui imp
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()
由于xpath未指向任何内容,因此出现NosTouchElementException错误
那怎么办
distance = browser.find_element_by_xpath(
"//*[contains(text(), 'Distance')]/span[1]"
).text
哎呀,有时候会失败,但我不明白为什么。例如,尽管响应页面中有带距离的span类,但对于起始LIRF和目标LEMD,它失败。这种事发生在你身上吗?我添加了time.sleep10,但仍然存在相同的问题。@Scala With from selenium.webdriver.common.by import by and from selenium.webdriver.support import预期的\u条件为EC,您是否尝试添加了\u元素的WebDriverWaitbrowser、delay.untelec.presence\u locatedBy.XPATH、//*[containstext,‘Distance']/span[1]?@Scala对我来说,它与您给出的示例一起工作,即从LIRF到LEMD。你有没有这样的案例?它是随机失败的,没有任何逻辑。当我添加WebDriverWaitbrowser时,延迟,一切都稳定了下来。谢谢如果它再次失败,我将打开另一个线程。