Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching and focusing a newly opened tab in selenium

Hello I am using selenium to click links and generally use an online web app.

I have trouble when I click a particular link which opens a new tab and performing an action in that newly opened tab. I have this code:

friend_link = browser.find_element_by_tag_name('a')
friend_link.click() # this is where new tab is opened

After which the webdriver(from my eyes) opens to the new tab without me having to call

browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

So all is good. New tab is opened on the webdriver. When I try to click a link on that newly opened tab, I get a 'No element' exception, meaning it couldn't find the element I was looking for.

Two questions:

1) Does the webdriver know that a newly opened tab was opened and to perform actions on that tab? Maybe I have to tell it. I tried

main_window = browser.current_window_handle
browser.switch_to_window(main_window)

which is supposed to refocus a newly opened tab, but no luck.

2) Is there a way to see if the computer knows that it's on the new tab?

like image 257
Ecko Avatar asked Oct 30 '22 10:10

Ecko


1 Answers

check driver.window_handles if it returns more than one instanc, the second one should be newly opened tab. Use driver.switch_to_window(instance-id) to switch it. See below:

>>> driver.window_handles
[u'CDwindow-608A7C64-A633-4DEC-B88F-6A2578C47669']
>>> driver.window_handles
[u'CDwindow-608A7C64-A633-4DEC-B88F-6A2578C47669', u'CDwindow-A2A95622-3146-4BF6-9E7A-7A6632A73C86']
>>> driver.current_window_handle
u'CDwindow-608A7C64-A633-4DEC-B88F-6A2578C47669'
>>> driver.switch_to.window("CDwindow-A2A95622-3146-4BF6-9E7A-7A6632A73C86")
>>> driver.current_window_handle
u'CDwindow-A2A95622-3146-4BF6-9E7A-7A6632A73C86'
>>> driver.get("http://www.amazon.com")
like image 162
Mesut GUNES Avatar answered Nov 15 '22 12:11

Mesut GUNES