当使用Selenium和Python在HTML中存在特定元素时,如何单击向下箭头键

问题描述 投票:0回答:2

[我希望python在浏览器或searh栏中的某个特定词(例如google)出现时,单击键盘上的某个键,例如向下箭头键。硒或os模块是否可以使用。有什么建议吗?

python selenium automation keyboard arrow-keys
2个回答
0
投票

您可以使用xpath搜索元素,以查找您要搜索的文本,例如$x('//*[.="Abdalla Roda"]'),然后使用sendKey()按下键


0
投票

当满足特定条件时,使用Selenium单击Arrow Down键,例如,我已通过以下步骤演示了此示例:

  • 打开网址https://www.google.com/
  • 等待Google主页搜索框元素,即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)
      
    • 浏览器快照:

Keys.DOWN

PS:实现上述逻辑,您还可以单击Arrow UpArrow LeftArrow Right键。

© www.soinside.com 2019 - 2024. All rights reserved.