代码之家  ›  专栏  ›  技术社区  ›  ScalaBoy

NoSuchElementException:消息:无法定位元素://span[contains(text(),'Distance')]

  •  -1
  • ScalaBoy  · 技术社区  · 6 年前

    我有这个代码,但它失败了,出现了错误 NoSuchElementException: Message: Unable to locate element: //span[contains(text(), 'Distance')] .

    这是 page 我用来刮的。对于我的输入数据, distance 应等于:

    261.30(海里)/300.76(英里)/483.93(公里)

    我的代码有什么问题?我检查了所有元素的指定是否正确。

    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()
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   keepAlive    6 年前

    你得到了一份工作 NoSuchElementException 错误,因为xpath未指向任何内容。

    那么...怎么样

    distance = browser.find_element_by_xpath(
        "//*[contains(text(), 'Distance')]/span[1]"
    ).text