问题
I am using selenium and PhantomJS for testing. I followed Selenium's simple usage, but send_keys doesn't work on PhantomJS, it works on Firefox. Why? I have to use button.click()
instead?
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.PhantomJS()
driver.get("http://www.python.org/")
elem = driver.find_element_by_id("q")
elem.clear()
elem.send_keys("python")
elem.send_keys(Keys.RETURN)
# button = driver.find_element_by_id('submit')
# button.click()
print driver.title
print driver.page_source
driver.close()
回答1:
I highly suspect it's just timing issue.
Selenium's click()
will wait for page to load if it is redirected after clicking, while send_key()
doesn't wait. (PhantomJS is headless, which is faster than Firefox)
Please try add some sleep like time.sleep(5)
after elem.send_keys(Keys.RETURN)
, before print driver.title
, and see if you can get the result you want.
In real testing project, you just need to use WebDriverWait until driver.title
equals to the value you want.
来源:https://stackoverflow.com/questions/17800573/selenium-phantomjs-send-keys-doesnt-work