如何使用Selenium和Python模拟在HTML中存在特定元素时按下向下箭头键
我希望python在浏览器或搜索栏中的某个位置出现特定单词(例如google)时,单击键盘上的某个键(例如向下箭头键)。是否可以使用selenium或操作系统模块。有什么建议吗?您可以使用xpath搜索您正在搜索的文本的元素,例如,如何使用Selenium和Python模拟在HTML中存在特定元素时按下向下箭头键,python,selenium,automation,keyboard,arrow-keys,Python,Selenium,Automation,Keyboard,Arrow Keys,我希望python在浏览器或搜索栏中的某个位置出现特定单词(例如google)时,单击键盘上的某个键(例如向下箭头键)。是否可以使用selenium或操作系统模块。有什么建议吗?您可以使用xpath搜索您正在搜索的文本的元素,例如,$x('/*[..=“text”])然后使用sendKey()按键您可以使用xpath搜索您正在搜索的文本的元素,例如,$x('/*[..=“text”])),然后使用sendKey()按下键在满足特定条件时单击向下箭头键,如我通过以下步骤演示的示例: 打开url
$x('/*[..=“text”])
然后使用sendKey()
按键您可以使用xpath搜索您正在搜索的文本的元素,例如,$x('/*[..=“text”]))
,然后使用sendKey()
按下键在满足特定条件时单击向下箭头键,如我通过以下步骤演示的示例:
- 打开url
- 等待Google主页搜索框元素,即,
可点击By.NAME,“q”
- 发送字符序列selenium
- 等待自动建议可见
- 在向下箭头键上单击两次
- 代码块:
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)
- 浏览器快照:
- 代码块:
- 打开url
- 等待Google主页搜索框元素,即,
可点击By.NAME,“q”
- 发送字符序列selenium
- 等待自动建议可见
- 在向下箭头键上单击两次
- 代码块:
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)
- 浏览器快照:
- 代码块:
@AbdallaRoda对此答案有何反馈?@AbdallaRoda对此答案有何反馈?