So I have a test case: When clicking a button a new window is opened. To switch to that new window I use:
window_after = self.driver.window_handles[1]
self.driver.switch_to.window(window_after)
When I execute the test case in normal Chrome browser, there is no error and I receive a positive outcome. But when I use headless Chrome, I'm getting an error: "selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//h1[text()='Trip Terms and Conditions']" (Session info: headless chrome=78.0.3904.87)" This is how I use the headless Chrome:
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
driver = webdriver.Chrome(options=chrome_options)
So as I understand, headless Chrome can't switch to the new opened window. Is there a error in the code? What I'm doing wrong?
Thank you.
-
Do you wait for the element? Maybe the switch is too fast headless?Niels van Reijmersdal– Niels van Reijmersdal2019年11月01日 12:15:34 +00:00Commented Nov 1, 2019 at 12:15
-
Yes, sure. Same result.rodut– rodut2019年11月02日 10:21:49 +00:00Commented Nov 2, 2019 at 10:21
2 Answers 2
I don't know the exact answer but maybe can help find the solution. Have you tried finding out if this is actually the correct window handle? You could try debugging by:
- Counting the number of window handles
- Opening the last window handle in stead of exactly
[1]
- Reading the DOM of all window handles to see what is found by executing this script over each handle and writing to console or something
driver.execute_script("return document.documentElement.outerHTML")
-
As I wrote before, when I execute the test case in normal Chrome browser, there is no error and I receive a positive outcome. Thank you.rodut– rodut2019年11月02日 10:25:15 +00:00Commented Nov 2, 2019 at 10:25
-
Yes I read your post. Have you tried debugging to find out if headless tries to find the element in the correct window/tab ? Maybe there is a bug in headless mode.Jeroen Lamberts– Jeroen Lamberts2019年11月04日 07:38:33 +00:00Commented Nov 4, 2019 at 7:38
I don't know if you already solved the problem, but I had the same problem mentioned in the post.
In browser mode I was able to switch between active tabs, however in headless mode this was not possible, self.driver.window_handles
always returned 1.
After much searching, I found a possible solution. In Chrome's options I added the window-size tag which seemed to resolve it. My options looked like this:
options = webdriver.ChromeOptions()
options.add_argument("--headless")
options.add_argument("--window-size=1920,1080")
OBS: sorry if some words don't make sense, text fully translated by google translate.
Explore related questions
See similar questions with these tags.