Can't send keys selenium webdriver python

元气小坏坏 提交于 2020-01-21 22:26:13

问题


Trying to execute simple test

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()

driver.get('http://google.com')
driver.find_element_by_name('q')
driver.send_keys('hey')

And getting the error

Traceback (most recent call last):
  File "C:/webdriver/test.py", line 8, in <module>
    driver.send_keys('hey')
AttributeError: 'WebDriver' object has no attribute 'send_keys'

What's the problem?


回答1:


WebDriver instance does not have send_keys() method. That's what the error is actually about:

'WebDriver' object has no attribute 'send_keys'

Call send_keys() on a WebElement instance which is returned by find_element_by_*() methods - find_element_by_name() in your case:

element = driver.find_element_by_name('q')
element.send_keys("hey")

And just FYI, there is also an ActionChains class which is useful do build up chains of actions or apply more complex actions like drag&drop or mouse move. It's an overhead in this case, but just for the sake of an example:

from selenium.webdriver.common.action_chains import ActionChains

actions = ActionChains(driver)
actions.move_to_element(element).send_keys("hey").perform()



回答2:


You must change the reference element

driver.get('http://google.com')
elem.find_element_by_name('q')
elem.send_keys('hey')



回答3:


Did you try changing your reference element. It would be a good practice if you call webdriver using different reference. Your code after changing reference.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Firefox()
driver.get('http://google.com')
#Firefox Webdriver is created and navigated to google.

elem = driver.find_element_by_name('q')
elem.send_keys('hey',Keys.RETURN)
#Keys.RETURN = Pressing Enter key on keyboard

time.sleep(5)
driver.close()



回答4:


Its with the version of selenium which is causing the issue. I faced the same issue.

Its with the selenium version 3.3.3 which has the compatibility problem.

Try: pip uninstall selenium pip install selenium==3.3.1

Hope it works.



来源:https://stackoverflow.com/questions/32835008/cant-send-keys-selenium-webdriver-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!