Selenium/Python handling tabs on Chrome : NoSuchWindowException - python

I am trying to open/close tabs with chrome as my webdriver.
driver=webdriver.Chrome()
driver.get("http://www.google.com")
driver.find_element_by_xpath('//*[#id="zV9nZe"]/div') #accepting cookies
driver.execute_script("window.open('https://google.com','_blank')") #opening a new tab
driver.switch_to.window(driver.window_handles[0]) #switching back to previous tab
driver.close() #closing previous tab
driver.switch_to(driver.current_window_handle) #switching to current tab
driver.execute_script("window.open('https://google.com','_blank')") #opening a new tab
However when I try to open a new tab after closing the previous one I get the following error NoSuchWindowException: Message: no such window: target window already closed
I tried closing or opening tabs using the following code as a workaround
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
However both do nothing.

So I think I managed to fix this issue. First of all it appears that with Chromedriver sendkeys method won't work correctly with shortcuts -see Selenium with Python: send_keys() doesn't work on headless ubuntu .
Secondly by switching to the new window using
driver.switch_to.window(driver.window_handles[-1])
Instead of
driver.switch_to(driver.current_window_handle)
seems to fix this issue.
Thus the complete solution would be
driver=webdriver.Chrome()
driver.get("http://www.google.com")
driver.find_element_by_xpath('//*[#id="zV9nZe"]/div') #accepting cookies
driver.execute_script("window.open('https://google.com','_blank')") #opening a new tab
driver.switch_to.window(driver.window_handles[0]) #switching back to previous tab
driver.close() #closing previous tab
driver.switch_to.window(driver.window_handles[-1]) #switching to current tab
driver.execute_script("window.open('https://google.com','_blank')") #opening a new tab
Hope I helped some of you struggling with Selenium and tabs handling.

Related

Opening a new tab with undetected chrome driver python

I was trying to open another tab using undetected chrome driver in python. I found that when I use the javascript way chrome blocks my pop-up. I can't figure out what I'm doing wrong. Here's my code.
options = webdriver.ChromeOptions()
options.add_argument('--disable-popup-blocking')
if __name__ == '__main__':
chrome = uc.Chrome(options=options)
time.sleep(1)
chrome.get("https://www.google.com")
chrome.execute_script("window.open('https://google.com','_blank')")
You need to do some action or use sleep after opening the new tab, otherwise the browser will close immediately after opening a new tab. Try adding time.sleep(30) to the end of your code.

multiple chrome windows with webdriver python

I would like to open multiple chrome windows. Once they open, however, they close at the end of the for loop. can anyone help me? thank you so much
for i in range(numeroTask):
i = webdriver.Chrome(PATH)
i.get("https://www.youtube.com/")
This is how you can do it. I'm using window.open() to open a new tab and then driver.switch_to.window to switch to it, so you can open a url.
from selenium import webdriver
driver = webdriver.Chrome()
windows_count = 3
for i in range(windows_count):
# Opens a new tab
driver.execute_script("window.open()")
# Switch to the newly opened tab
driver.switch_to.window(driver.window_handles[i])
# Navigate to new URL in new window
driver.get("https://youtube.com")
# Close all tabs:
driver.quit()
Hopefully this helps, good luck!
Updated, way to do it with multiple chrome windows:
from selenium import webdriver
driver = webdriver.Chrome()
windows_count = 3
for i in range(windows_count):
# Opens a new tab
driver.execute_script('window.open("https://youtube.com", "_blank", "resizable=yes, scrollbars=yes, titlebar=yes, width=800, height=900, top=10, left=10");')
# Close all windows:
driver.quit()
DO you want to open simultaneously? Then you should try threads, async functions.

How to change URL in Selenium without opening new tab (python)?

I saw some .navigate() functions to do that in java but it's not in python.
So, how can I just change the URL of currently opened window without opening a new tab?
Just call driver.get('yourURL') again. Example:
driver = webdriver.Chrome()
driver.get('https://google.com')
print(driver.current_url)
driver.get('https://gmail.com/')
print(driver.current_url)
Output:
https://www.google.com/
https://www.google.com/intl/id/gmail/about/#

Unable to focus on new tab in firefox when clicking on the link that opens a new tab using selenium and python

element=driver.find_element_by_xpath("html/body/footer/div/div[1]/section/div/div/div[2]/div[1]/ul/li[9]/div/div/a")
driver.execute_script("arguments[0].click();", element)
print(driver.title)
The xpath mentioned is that of a link. In the above code after driver.execute_script is executed the link is opened in a new tab but driver.title still shows the title of the old tab as a result a new element in the new tab could not be identified. Can someone help me here please.
Selenium version used: 3.11.0
Firefox version used: 47.0.2
geckodriver version used: 0.14
If after clicking on next button, Page opens in a new tab then you have to switch the focus of WebDriver to that window.
window_before = driver.window_handles[0]
# Click on next button on Page 1.
# Opens a new tab
window_after = driver.window_handles[1]
driver.switch_to_window(window_after)
#performs some operations on Page 2.
print(driver.title)
driver.close()
driver.switch_to.window(window_before )

Selenium won't open a new URL in a new tab (Python & Chrome)

I want to open quite a few URLs in different tabs using Selenium WebDriver & Python.
I am not sure what is going wrong:
driver = webdriver.Chrome()
driver.get(url1)
time.sleep(5)
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL+'t')
url2 = 'https://www.google.com'
driver.get(item2)
I looked up tutorials and it seems to me as though this code should do what I want. What actually happens is the browser opens, url1 opens as it should, a new tab opens as it should but url2 then loads in the original tab instead of the new one (even though the new tab appears to be the active one).
(I am using Chrome because when using Firefox I can't get it to load any URLs at all. Firefox opens but does not get the url requested. I have tried to find a solution to this but to no avail.)
Is there anything I can change in my code to get the new URL to open in the new tab?
Thanks for your help!
Here is a simple way, platform independent:
Code:
driver.execute_script("window.open('http://google.com', 'new_window')")
Switching back to the original tab:
Code:
driver.switch_to_window(driver.window_handles[0])
Checking the current title to be sure you are on the right page:
Code:
driver.title
For everything else, have fun!
There is a bug in ChromeDriver that prevents ctrl/command+T from working:
I canĀ“t open new tab in ChromeDriver
What you can do, as a workaround, is to open a link in a new tab and then switch to a new window using the switch_to.window(). Working sample:
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get("https://www.google.com")
# open a link in a new window
actions = ActionChains(driver)
about = driver.find_element_by_link_text('About')
actions.key_down(Keys.CONTROL).click(about).key_up(Keys.CONTROL).perform()
driver.switch_to.window(driver.window_handles[-1])
driver.get("https://stackoverflow.com")
Now the last driver.get() would be performed in a newly opened tab.
An alternative way to open a new window is to use JavaScript and the window handler to switch between them.
driver = webdriver.Chrome()
# Open a new window
# This does not change focus to the new window for the driver.
driver.execute_script("window.open('');")
# Switch to the new window
driver.switch_to.window(driver.window_handles[1])
driver.get("http://stackoverflow.com")
# close the active tab
driver.close()
# Switch back to the first tab
driver.switch_to.window(driver.window_handles[0])
driver.get("http://google.se")
# Close the only tab, will also close the browser.
driver.close()
If you look at your browser while you're executing it will look like the new window has focus, but to the webdriver, it doesn't. Don't be fooled by the visual. Also remember to select a new window handler when you close a tab as it will set the driver.current_window_handle to
selenium.common.exceptions.NoSuchWindowException:
Message: no such window: target window already closed from unknown error: web view not found
(Session info: chrome=<Your version of chrome>)
(Driver info: chromedriver=<Your chrome driver version> (<string of numbers>),platform=<Your OS>)
on .close() and it will throw that error if you try to do stuff with the driver at that stage.
you need to maximize your chrome for this
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.google.com/")
e = driver.find_element_by_tag_name("body")
ActionChains(driver).key_down(Keys.CONTROL).click(e).send_keys("k").key_up(Keys.CONTROL).perform()
here key_down(Keys.CONTROL) will hold down ctrl key, to get focus on page i am clicking body of the page, then click k

Categories