无法使用selenium和python提交密钥

时间:2016-03-14 20:44:47

标签: python selenium selenium-webdriver

以下是我试图运行的代码

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

#Create a new firefox session
browser=webdriver.Firefox()
browser.maximize_window()


#navigate to app's homepage
browser.get('http://demo.magentocommerce.com/')

#get searchbox and clear and enter details.
browser.find_element_by_css_selector("a[href='/search']").click()
search=browser.find_element_by_class_name('search-input')

search.click()
time.sleep(5)
search.click()
search.send_keys('phones'+Keys.RETURN)

但是,我无法使用send_keys提交手机。 我在某个地方出错了吗?

其次是否可以始终使用x-path定位元素而不依赖于id / class / css-selections等?

1 个答案:

答案 0 :(得分:1)

您感兴趣的输入元素具有search_query类名。要在不使用硬编码time.sleep()延迟的情况下使其工作,请在向其发送密钥之前使用Explicit Wait等待搜索输入元素可见。工作代码:

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

browser = webdriver.Firefox()
browser.maximize_window()
wait = WebDriverWait(browser, 10)

browser.get('http://demo.magentocommerce.com/')

browser.find_element_by_css_selector("a[href='/search']").click()

search = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "search-query")))
search.send_keys("phones" + Keys.RETURN)