[我希望python在浏览器或searh栏中的某个特定词(例如google)出现时,单击键盘上的某个键,例如向下箭头键。硒或os模块是否可以使用。有什么建议吗?
您可以使用xpath搜索元素,以查找您要搜索的文本,例如$x('//*[.="Abdalla Roda"]')
,然后使用sendKey()
按下键
当满足特定条件时,使用Selenium单击Arrow Down键,例如,我已通过以下步骤演示了此示例:
By.NAME, "q"
可单击。在Arrow Down键上单击twice。
代码块:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get('https://www.google.com/')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, "q"))).send_keys("Selenium")
WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "ul[role='listbox'] li")))
driver.find_element_by_css_selector('body').send_keys(Keys.DOWN)
driver.find_element_by_css_selector('body').send_keys(Keys.DOWN)
浏览器快照:
PS:实现上述逻辑,您还可以单击Arrow Up,Arrow Left和Arrow Right键。