I run .click()
on the link and a new tab opens, the focus becomes on it
self.find_element(PageLocators.BANNER).click()
find_element
is my wrapper over the standard function, I just added an explicit wait before the element appears in the DOM:
def find_element(self, locator, time=10):
return WebDriverWait(self.driver, time).until(
EC.presence_of_element_located(locator),
f"Couldn't find element by locator {locator}",
)
After .click()
, I am on a new page, the tab automatically switches to it, but the driver.current_url remains the same. But if you uncomment the line below, then everything works and current_url is updated.
def block_exist(self):
try:
# self.driver.switch_to.window(self.driver.window_handles[1]) <--- current_url is not updated without this line
self.find_element(PageLocators.BLOCK)
return True
except:
return False
Why do I need to use self.driver.switch_to.window(self.driver.window_handles[1])
if the focus is automatically set to a new tab in the browser?
Selenium does not change focus to a newly opened window until you tell it to.
Without more info, it's hard to answer the rest of your question. If I were to guess, it's because the locator you are using matches an element on the original page as well so it's finding that one.