硒超时异常

时间:2019-05-21 20:09:16

标签: python selenium selenium-webdriver

我正在尝试从Google Flight搜索页面中获取最便宜的航班价格。 即使使用WebDriverWait,我也会遇到超时错误。这是我的代码:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

example_url = 'https://www.google.com/flights?hl=it#flt=/m/07_pf./m/01f62.2019-05-24;c:EUR;e:1;0px:2;sd:1;t:f;tt:o'

def get_price(url):
        driver = webdriver.Firefox()
        driver.get(url)
        try:
             wait = WebDriverWait(driver, 20)
             element = wait.until(EC.presence_of_element_located((By.CLASS_NAME, '.gws-flights-results__cheapest-price')))
             print(element)
        finally:
             price = driver.find_element_by_css_selector('.gws-flights-results__cheapest-price').text
             driver.quit()
        price = float(price.split(' ')[0])
        driver.quit()
        return price       


price = get_price(example_url)
print(price)

我收到此错误:

Traceback (most recent call last):
  File "semplice.py", line 23, in <module>
    price = get_price(example_url)
  File "semplice.py", line 13, in get_price
    element = wait.until(EC.presence_of_element_located((By.CLASS_NAME, '.gws-flights-results__cheapest-price')))
  File "/home/andrea/ENTER/lib/python3.4/site-packages/selenium/webdriver/support/wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

终端上未打印任何消息。只是这就是信息。 问题出在哪里 ?

2 个答案:

答案 0 :(得分:2)

@kafels是正确的,您不需要在类名定位符前面加点。但是,一旦解决此问题,您实际上就不需要在最后进行第二次搜索。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

example_url = 'https://www.google.com/flights?hl=it#flt=/m/07_pf./m/01f62.2019-05-24;c:EUR;e:1;0px:2;sd:1;t:f;tt:o'

def get_price(url):
    driver = webdriver.Firefox()
    driver.get(url)
    wait = WebDriverWait(driver, 20)
    try:
        element = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 
                                                             'gws-flights-results__cheapest-price')))
    except Exception as exc:
        raise
    finally:
        # no need to look for the element here since you do it in the try section.
        driver.quit()

    print(element)
    price = element.text
    price = float(price.split(' ')[0])
    return price

price = get_price(example_url)
print(price)

答案 1 :(得分:1)

错误是因为您传递点以按类名称查找元素:

element = wait.until(EC.presence_of_element_located((By.CLASS_NAME, '.gws-flights-results__cheapest-price'))

将其更改为:

element = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'gws-flights-results__cheapest-price')))