0

I've been trying to switch tabs in selenium for a day now and I just can't get it. I want to do web scraping on selenium and open the links in tabs instead of opening a new browser everytime since that takes a lot of resources from the computer and gives me another problem. I want the tabs to go in a loop with a couple of different links and then check for elements. What code can I use to open the links in new tabs and switch to that tab to then later check for elements? I'm using selenium with opera. Thank you!

Coder
  • 109
  • 2
  • 11

1 Answers1

0

I had this struggle in the past. See below minimal working example:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://stackoverflow.com/")
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[1])
driver.get("https://github.com/")
driver.switch_to.window(driver.window_handles[0])

The key is making sure that you switch your driver to that window. Simply opening up the tab is not enough to begin scraping the new url.

Luke Hamilton
  • 637
  • 5
  • 19
  • If I use your piece of code, and change url to my url It will open up data; and then a nameless tab. If i write driver.get before the whole code, it will open up the url and then a nameless tab instead of the url i actually want to. Thus the console is giving me "InvalidArgumentException: Message: invalid argument: 'name' must be a string – Coder Nov 22 '21 at 18:04
  • @Coder I just made an edit to my code with a minimal working example. It should open up a browser, get stackoverflow, switch tabs, get github, then switch back to the stack overflow tab. Let me know if that works. – Luke Hamilton Nov 22 '21 at 18:12
  • It does open up stackoverflow but then it opens up a new tab named "nameless" and gives me selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: 'name' must be a string – Coder Nov 22 '21 at 18:20
  • @Coder if you want solution then you should show all details in question - without your `url` it is useless. And better show your code. – furas Nov 22 '21 at 20:04
  • I did ask a new question recently about it, if you know the answer then feel free to check it out – Coder Nov 22 '21 at 20:22
  • @Coder I see that, have you tried to run it without importing the options? – Luke Hamilton Nov 22 '21 at 21:12