selenium.common.exceptions.InvalidArgumentException: Message: The argument provided is not valid: 'name' must be a string when transitioning between window handles using Selenium

Whenever I try to use the following code snippet:

driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[1])
driver.get(url)
driver.switch_to.window(driver.window_handles[0])

An error is thrown at me.

selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: 'name' must be a string

The same issue arises when any code containing

driver.switch_to.window(driver.window_handles[1])
is executed. This problem completely disrupts the functionality of the code. I am using Opera browser and it's becoming quite frustrating.

Complete traceback:

Traceback (most recent call last):
  File "C:\Users\user\PycharmProjects\websitemonitorcsshtml\switchtab.py", line 11, i
n <module>
    driver.switch_to.window(driver.window_handles[1])
  File "C:\Users\user\PycharmProjects\Giraffe\venv\lib\site-packages\selenium\webdriv
er\remote\switch_to.py", line 134, in window
    self._w3c_window(window_name)
  File "C:\Users\user\PycharmProjects\Giraffe\venv\lib\site-packages\selenium\webdriv
er\remote\switch_to.py", line 143, in _w3c_window
    send_handle(window_name)
  File "C:\Users\user\PycharmProjects\Giraffe\venv\lib\site-packages\selenium\webdriv
er\remote\switch_to.py", line 139, in send_handle
    self._driver.execute(Command.SWITCH_TO_WINDOW, {'handle': h})
  File "C:\Users\user\PycharmProjects\Giraffe\venv\lib\site-packages\selenium\webdriv
er\remote\webdriver.py", line 418, in execute
    self.error_handler.check_response(response)
  File "C:\Users\user\PycharmProjects\Giraffe\venv\lib\site-packages\selenium\webdriv
er\remote\errorhandler.py", line 243, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: 'name'
 must be a string
  (Session info: chrome=95.0.4638.69)
  (Driver info: operadriver=95.0.4638.54 (d31a821ec901f68d0d34ccdbaea45b4c86ce543e-ref
s/branch-heads/4638@{#871}),platform=Windows NT 10.0.19042 x86_64)

Below is the complete piece of code:

from selenium import webdriver 
from selenium.webdriver.opera.options import Options 

options = Options() 
options.add_experimental_option('excludeSwitches', ['enable-logging']) 
DRIVER_PATH = 'C:\Python27\Scripts\operadriver.exe' 
driver = webdriver.Opera(options=options, executable_path=DRIVER_PATH)
driver.get("stackoverflow.com/")
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[1])
driver.get("github.com/")
driver.switch_to.window(driver.window_handles[0])

Answer №1

Window Switching

  1. To switch windows in Selenium using Python, follow these steps:

    store the parent window handle for future use:
    window_before  = driver.current_window_handle
    
  2. After opening a new window, store all window handles in a list.

    windows_after = driver.window_handles
    
  3. Instead of using indexes to switch windows, utilize List Comprehension to find the new window handle:

    new_window = [x for x in windows_after if x != window_before][0]
    

Solution

Here is the complete code block for window switching:

driver.get("https://stackoverflow.com/")
window_before = driver.current_window_handle
print("First Window Handle is : %s" %window_before)
print("Page Title before Tab Switching is : %s" %driver.title)
driver.execute_script("window.open('','_blank');")
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
windows_after = driver.window_handles
new_window = [x for x in windows_after if x != window_before][0]
driver.switch_to.window(new_window)
driver.get("https://www.selenium.dev/")
print("Second Window Handle is : %s" %new_window)
print("Page Title after Tab Switching is : %s" %driver.title)
driver.switch_to.window(window_before)
print("Window Handle is : %s" %window_before)
print("Page Title after Reverse Tab Switching is : %s" %driver.title)
driver.quit()

Don't forget to include the following imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Console Output:

First Window Handle is : CDwindow-9E723D48DFB59B9B6BCB992EFE3C6695
Page Title before Tab Switching is : Stack Overflow - Where Developers Learn, Share, & Build Careers
Second Window Handle is : CDwindow-9CCD4B7DD7F5916788A422F24D476BC8
Page Title after Tab Switching is : Selenium
Window Handle is : CDwindow-9E723D48DFB59B9B6BCB992EFE3C6695
Page Title after Reverse Tab Switching is : Stack Overflow - Where Developers Learn, Share, & Build Careers

Answer №2

If you are encountering issues when trying to switch to a tab that may not have been fully created yet, it could be due to timing. To check this, print out the list of available window_handles after calling window.open and verify if it contains the expected number of tabs. If there is only one tab listed and you are attempting to access a second one, an error message stating that 'name' (tab id) must be a string will be displayed.

To resolve this issue, it is advisable to wait until the number of tabs increases (after opening something in the new tab) and then proceed with switching once this condition has been met.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PhantomJS occasionally fails to close (while using Python with Selenium)

Currently, I am utilizing selenium-python in combination with PhantomJS. The code structure is as follows: from selenium.webdriver import PhantomJS from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from se ...

Using the key from a nested CSV file as the primary key in Python

Sorry for the confusing title. I have a csv file with rows structured like this: 1234567, Install X Software on Y Machine, ServiceTicket,"{'id': 47, 'name': 'SERVICE BOARD', '_info': {'board_href': ' ...

Changing Field Order in csv Using Python (Utilizing Numpy or Pandas)

Can anyone assist me with achieving the following task? Image ID 20170101 20170106 20170111 A 0.31 0.1 0.2 B 0.3 0.2 0.1 C 0.11 0.12 0.13 D 0.3 0.3 0.4 ID DATES NDVI_ ...

When the Addmore button is clicked, a new text box with the same ID and class name will be generated and sent to the text box of ClientName

After clicking the add button, I encountered an issue where dynamically created text-boxes with the same id and class name were not allowing me to send text to the second or third text-box. List<WebElement> clientidtxt = driver.findElements(By.xpath ...

What is the most effective Xpath for retrieving text from <td> elements when there is text present in both?

I have the following XML that needs to be extracted: <div class="tab_product_details"> <table> <tbody> <tr>...</tr> <tr>...</tr> <tr>...</tr> <tr> ...

Error message: "The specified file could not be found in the

I am looking to integrate adb functions within a Python environment. When connecting adb in the terminal, everything seems to be working fine as seen below. $ adb --version Android Debug Bridge version 1.0.41 Version 31.0.3-7562133 Installed as /opt/homebr ...

An error of 'Address already being used' encountered while utilizing cookiecutter-flask

My operating system is OS X 10.14.3 and I am attempting to utilize the impressive cookiecutter-flask project. I have diligently followed the instructions provided in the README.rst: cookiecutter https://github.com/sloria/cookiecutter-flask.git # My test p ...

How can I locate the object labeled as "Current" in Selenium?

I am looking to use Selenium to navigate a menu using arrow keys—beginning with clicking the top menu item and then pressing "DOWN," "DOWN," ... The issue is that you always need to provide a specific element to send the "DOWN" key to. Is there a way t ...

Receiving a LoadError in Ruby selenium-webdriver while attempting to automate a script

I recently developed a selenium test in Ruby that is designed to navigate to a specific website and confirm the presence of a certain page element. The script functions correctly when run from the command line, but encounters an error when executed through ...

Watir does not have time to wait for the page to finish loading

Currently, when loading a page and clicking on an element within that page, I am relying on the sleep function. However, I find this method to be unreliable as the element disappears after some time. Clicking on (page1).buttonForNextPage @myvariable = ...

Python script to locate the identical sentence in two separate files

Hello there. I am a beginner in Python and need some help with finding code that can search for exact keywords in a text file within an HTML file. For example, looking for keywords from keyword.txt in data.html. Currently, the code is only matching the fir ...

Utilize an unspecified quantity of variables to store the results generated by a function

I am trying to use a method called __some_method. This method can return one parameter, two parameters, or any number of parameters. I need to call this method from another one and assign the returns to variables dynamically based on the number of returned ...

Combine an array with a JSON object in Python

Working with JSON in python3 and looking to add an array to a json object. Here's what I have so far: values = [20.8, 21.2, 22.4] timeStamps = ["2013/25/11 12:23:20", "2013/25/11 12:25:20", "2013/25/11 12:28:20"] myJSON = '{ Gateway: {"serial ...

Opera and Robotframework integration on Windows system

I am currently experiencing difficulty using Opera for website testing in Robotframework with SeleniumLibrary. I have discovered that the issue lies in the code's inability to handle Windows paths correctly. (On Windows, the default approach is to use ...

What are the steps to display a graph on a webpage using AJAX in Django?

I'm currently working on developing a weather forecast application, and I have implemented a date input box on the home page. When users enter a date and click submit, a graph displaying temperature data should be displayed. I have set up a URL that r ...

Looking for assistance to finish my code. Just a heads up, I am new to Python and could use

I'm currently working on a Python script that sends email notifications to check ping regularly at one-hour intervals. I've been facing challenges in creating a log file to store the ping details for mailing. My experience with the subprocess mod ...

Python - Retrieve the temporary directory

When attempting to write a file to the %temp% folder, I encounter an issue because each user has a different username. Is there a function or method in Python that can help me concatenate the folder path properly? I tried the following code, but it result ...

Utilizing Beautiful Soup for Web Scraping and Retrieving Dynamic JavaScript Code

When attempting to scrape websites like indeed, I am encountering an issue where Beautiful Soup is only returning plain JavaScript code. I am unsure whether I should try using something like selenium, or if Beautiful Soup alone can handle the task. e.pro ...

Unable to find the element within an iframe using Selenium while searching for a dictionary definition

Just starting out with Selenium and trying to automate filling out a web form to retrieve results as a Python dictionary. Here's what I have so far: from selenium.webdriver.common.keys import Keys from time import sleep driver = webdriver.Chrome() dr ...