运行这段代码会给我一个超时异常错误,为什么?

时间:2019-07-10 03:03:12

标签: python-3.x selenium selenium-chromedriver

我正在尝试构建一个脚本来自动使用硒填充文本框,但是我似乎无法使其正常工作。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
import time

browser = 
webdriver.Chrome('C:/Users/xiang/PycharmProjects/testo/chromedriver.exe')
browser.get('https://zbib.org/')
wait = WebDriverWait(browser, 10)
name = "form-control form-control form-control-lg id-input"

try:
    input = wait.until(ec.presence_of_element_located((By.CLASS_NAME, 
    name)))
finally:
    browser.quit()

我希望没有错误,并且浏览器/驱动程序也不会退出,但是我在终端中遇到此错误,浏览器/驱动程序会退出:

Traceback (most recent call last):
  File "C:/Users/xiang/PycharmProjects/testo/bib.py", line 14, in 
<module>
    input = wait.until(ec.presence_of_element_located((By.CLASS_NAME, 
name)))
  File "C:\Users\xiang\PycharmProjects\testo\venv\lib\site- 
   packages\selenium\webdriver\support\wait.py", line 80, in until
        raise TimeoutException(message, screen, stacktrace)
    selenium.common.exceptions.TimeoutException: Message:

请帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

您的代码肯定可以引发异常。 如果WebDriverWait在超时设置时间后仍不符合请求,将抛出TimeoutException。

您可以通过添加以下内容来忽略该异常:

from selenium.common.exceptions import TimeoutException
try:
    input = wait.until(ec.presence_of_element_located((By.CLASS_NAME, 
    name)))
except TimeoutException:
    pass
finally:
    browser.quit()

由于className包含空格,因此应使用CSS选择器。您的名称变量为:

name = ".form-control.form-control.form-control-lg.id-input"

您的代码应为:

from selenium.common.exceptions import TimeoutException
try:
    input = wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, 
    name)))
except TimeoutException:
    pass
finally:
    browser.quit()

要确保关闭浏览器,您还可以使用上下文管理器,如下所示:

name = ".form-control.form-control.form-control-lg.id-input"
chromedriver = 'C:/Users/xiang/PycharmProjects/testo/chromedriver.exe'

with webdriver.Chrome(chromedriver) as browser:
    browser.get('https://zbib.org/')
    wait = WebDriverWait(browser, 10)
    try:
        input = wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, name)))
    except TimeoutException:
        pass