Python / Selenium如何选择自动完成搜索栏的第一个选项

时间:2017-05-25 15:17:46

标签: python selenium

我正在尝试在this site的搜索栏中输入关键字,然后选择出现的第一个自动填充选项。如果我要手动执行此操作,我会在搜索栏中键入“remote”并按下键,然后按下我在下面的代码中尝试复制的输入,但它似乎正在跳过下键部分而不是选择第一个自动填充选项并转到搜索结果页,而不是this page,这是第一个自动填充选项。

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

driver = webdriver.Chrome()
driver.get("https://confluence.eits.uga.edu/dashboard.action")

elem = driver.find_element_by_id("quick-search-query")
elem.send_keys("remote")
elem.send_keys(Keys.ARROW_DOWN)
elem.send_keys(Keys.RETURN)

任何人都有任何想法为什么没有注册密钥或我没有使用正确的语法?

2 个答案:

答案 0 :(得分:0)

您仍然将密钥发送到触发搜索的搜索输入。相反,找到第一个快速搜索下拉选项并向其发送密钥:

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

driver = webdriver.Chrome()
driver.get("https://confluence.eits.uga.edu/dashboard.action")

elem = driver.find_element_by_id("quick-search-query")
elem.send_keys("remote")
elem.send_keys(Keys.ARROW_DOWN)

# wait for the first dropdown option to appear and open it
first_option = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".quick-search-dropdown li a")))
first_option.send_keys(Keys.RETURN)

答案 1 :(得分:0)

在这种情况下,您还可以尝试使用动作链,如下所示:

elem = driver.find_element_by_id("quick-search-query")
elem.send_keys("remote")

suggestion = driver.find_element_by_css_selector("#quick-search > fieldset > div > div > ol:nth-child(1) > li:nth-child(1) a > span")

actions = ActionChains(driver)
actions.move_to_element(suggestion )
actions.click(suggestion)
actions.perform()