Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send multiple tab key presses with Selenium

How can I send multiple tabs with Selenium?

When I run:

uname = browser.find_element_by_name("text")
uname.send_keys(Keys.TAB)

the next element is selected. When executing uname.send_keys(Keys.TAB) again nothing happens - actually the next element from uname is selected → so it is the same as when running it once.

How can I jump forward multiple times - basically as I would press TAB manually multiple times?

like image 220
pinas Avatar asked Feb 13 '16 20:02

pinas


3 Answers

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()
like image 194
alecxe Avatar answered Oct 16 '22 16:10

alecxe


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.

like image 43
syedelec Avatar answered Oct 16 '22 16:10

syedelec


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.

like image 38
jcomeau_ictx Avatar answered Oct 16 '22 16:10

jcomeau_ictx