Send multiple tab key presses with Selenium

前端 未结 6 885
栀梦
栀梦 2020-12-10 12:42

How can I send multiple tabs with Selenium?

When I run:

uname = browser.find_element_by_name("text")
uname.send_keys(Keys.TAB)
相关标签:
6条回答
  • 2020-12-10 13:02

    As the OP states: "actually the next element from uname is selected".

    After the first <TAB> key you have moved off the element, so no further <TAB>s will be recognized by that element. You need to locate the parent element and send keys to it.

    0 讨论(0)
  • 2020-12-10 13:04

    I think you can also write

    uname.send_keys(Keys.TAB + Keys.TAB + Keys.TAB + ... )
    

    It may be useful if you have only two or three commands to send.

    0 讨论(0)
  • 2020-12-10 13:06
    uname.send_keys(Keys.TAB, Keys.TAB, Keys.TAB..)
    

    worked for me.

    0 讨论(0)
  • 2020-12-10 13:13

    This syntax saved me:

    ActionChains(driver).send_keys(Keys.TAB * 2).perform()
    

    I tried using this from the accepted answer:

    actions = ActionChains(browser)
    actions.send_keys(Keys.TAB * 2)
    actions.perform()
    

    But since I wanted to later use three TABs in the same script, I ran into problems. The thing is that actions.send_keys(Keys.TAB * 3) simply adds to the previous lines in actions in the same script. So after the second time I use this line, instead of desired three TAB keys pressed I get five (i.e. 2 + 3). Furthermore, ActionChains.reset_actions() does not seem to work.

    0 讨论(0)
  • 2020-12-10 13:17

    Use Action Chains:

    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.action_chains import ActionChains
    
    N = 5  # number of times you want to press TAB
    
    actions = ActionChains(browser) 
    for _ in range(N):
        actions = actions.send_keys(Keys.TAB)
    actions.perform()
    

    Or, since this is Python, you can even do:

    actions = ActionChains(browser) 
    actions.send_keys(Keys.TAB * N)
    actions.perform()
    
    0 讨论(0)
  • 2020-12-10 13:18

    sendkeys(Keys.Tab, Keys.Tab, Keys.Tab) is working fine.

    0 讨论(0)
提交回复
热议问题