Sam00000000
Sam00000000

Reputation: 17

driver.close() doesn't close the current tab in selenium

I have a selenium webautomation program for tradingview. It all stays in one tab but when I open a new tab/link which it than switches to and which I than want to close after that, it closes the original tab. It looks like this:

for i in range(1, 1001):
input_ = '/html/body/div[8]/div/div[4]/table/tbody/tr[x]/td[1]/div/div[2]/a' 
list_input_ = list(input_) 
list_input_[44] = str(i)  
input_ = ''.join(list_input_)
stock = driver.find_element_by_xpath(input_) 
stock.click()
time.sleep(5)
driver.close() 
print(input_)
if i > 9:
    break 

The stock = driver.find_element_by_xpath(input_) and stock.click() opens the new tab/link to the left. But than driver.close() closes the tab I was previously in. I want it close the tab that it just opened and that I'm currently in. Which it supposed to do. It also seems like that none of the selenium commands work on this newly opened tab and only work on the original tab.

The copied element of the link it opens looks like this:<a class="tv-screener__symbol apply-common-tooltip" href="https://www.tradingview.com/symbols/NASDAQ-STAF/" target="_blank" rel="noopener">STAF</a>

Did I do something wrong here? Thanks in advance

Upvotes: 1

Views: 589

Answers (1)

Sushil
Sushil

Reputation: 5531

It is because you haven't switched focus to the new tab that you have opened. To switch focus to the newly opened tab, use this line:

driver.switch_to.window(driver.window_handles[1])

This line switches the focus to the 2nd tab that is open your browser. Then, you can perform the operations that you want in this tab. Then if you want to close this tab, then just use:

driver.close()

This would close the 2nd tab (the tab that is currently in focus).

Upvotes: 1

Related Questions