AttributeError:'WebDriver'对象不具有带有send_keys的属性'send_keys'

时间:2019-01-20 01:25:36

标签: python selenium selenium-webdriver webdriver sendkeys

我写了一个简单的函数。 go_to_url的用途,因此我们可以设置页面的最大加载时间。如果页面未在timeout_limit中加载,则我们将尝试再次加载该页面。但是,如果页面确实无法在规定的时间内加载并进入异常状态,我将收到错误消息。

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException

def go_to_url(driver, url, timeout_limit):
    while True:
        try:
            driver.set_page_load_timeout(timeout_limit)
            driver.get(url)
            break;
        except TimeoutException:
            driver.send_keys(Keys.ESCAPE)
            print('Failed to load, reloading page')

options = webdriver.ChromeOptions()
options.add_argument("--incognito")
driver = webdriver.Chrome(options=options)

go_to_url(driver, "http://www.emba.com.tw/", 4)

错误:

Traceback (most recent call last):
  File "test.py", line 15, in go_to_url
    driver.get(url)
  File "C:\Users\pc\AppData\Local\Programs\Python\Python37-32\lib\site-packages
\selenium\webdriver\remote\webdriver.py", line 333, in get
    self.execute(Command.GET, {'url': url})
  File "C:\Users\pc\AppData\Local\Programs\Python\Python37-32\lib\site-packages
\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\pc\AppData\Local\Programs\Python\Python37-32\lib\site-packages
\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: timeout
  (Session info: chrome=71.0.3578.98)
  (Driver info: chromedriver=2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f743
87),platform=Windows NT 6.3.9600 x86_64)


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 25, in <module>
    go_to_url(driver, "http://www.emba.com.tw/", 4)
  File "test.py", line 18, in go_to_url
    driver.send_keys(Keys.ESCAPE)
AttributeError: 'WebDriver' object has no attribute 'send_keys'

1 个答案:

答案 0 :(得分:0)

您的代码块接近完美。

此错误消息...

AttributeError: 'WebDriver' object has no attribute 'send_keys'

...表示 WebDriver 实现没有作为 send_keys

的属性 表示一个selenium.webdriver.remote.webelement元素的

DOM包含方法send_keys(*value),其定义为:

send_keys(*value)

 Simulates typing into the element.

因此,必须在元素上关联适当的调用send_keys()的方式,如下所示:

driver.find_element_by_css_selector("input.string").send_keys("Yuri")