在这种情况下,如何使用Selenium、Python和动作链模拟按键?

2024-10-03 00:29:21 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在Windows/Mac上的任意位置按CTRL+SHIFT+2时,我会打开一个弹出的(PhraseExpress)表单。我想用硒来模拟它。理想情况下,它可以在Windows和Mac上运行。现在我尝试让它在Windows上使用send_键和ActionChains

def open_form() -> None:
    """function to open the corresponding phraseexpress form (with a hotkey)."""
    bodyElement = WebDriverWait(driver, 40).until(
            EC.element_to_be_clickable((By.TAG_NAME, "body"))) #get a random element to perform send-keys action on.

    # create action chain object
    actions = ActionChains(driver)

  if fullstring == "Note 2":
        if platform == "win32": #if on Windows
            actions.key_down(Keys.CONTROL).key_down(Keys.SHIFT).send_keys_to_element(bodyElement, "2").key_up(Keys.SHIFT).key_up(Keys.CONTROL).perform()
            #actions.key_down(Keys.CONTROL).key_down(Keys.SHIFT).send_keys('2').key_up(Keys.SHIFT).key_up(Keys.CONTROL).perform() # I tried this as well
            #pyautogui.hotkey('ctrl', 'shift', '2') #This is working but I would like to use the above method instead, hoping it will work on Mac as well. This hotkey does not work on Mac. I think the hotkey is executed in Terminal instead of the OS, hence nothing happens. 
        print("You opened PhraseExpress for Note 2")
 

terminal中的输出为“You opened PhraseExpress for Note 2”,但表单不会弹出。按键不会触发操作系统上的窗体。你知道能做什么吗?当pyautogui.hotkey()工作时,为什么此操作不起作用


Tags: thetokeysendshiftonwindowsmac