Pavan Kumar T S
Pavan Kumar T S

Reputation: 1559

Force page to open in new window selenium-web-driver python

How do i force a link to open in new window in selenium-web-driver python and switch to it extract data and close it currently i am using following code

for tag in self.driver.find_elements_by_xpath('//body//a[@href]'):
            href = str(tag.get_attribute('href'))
            print href
            if not href:
                continue
            window_before = self.driver.window_handles[0]
            print window_before
            ActionChains(self.driver) \
                .key_down(Keys.CONTROL ) \
                .click(tag) \
                .key_up(Keys.CONTROL) \
                .perform()
            time.sleep(10)
            window_after = self.driver.window_handles[-1]
            self.driver.switch_to_window(window_after)
            print window_after
            time.sleep(10)
            func_url=self.driver.current_url
            self.driver.close()
            self.driver.switch_to_window(window_before)

problem

  1. the above code does not force if it hits a link with

    <a href="" target="_blank">something</a>

  2. after going through some two links it stales printing

    StaleElementReferenceException: Message: The element reference is stale. Either the element is no longer attached to the DOM or the page has been refreshed.

Upvotes: 2

Views: 4049

Answers (1)

Andersson
Andersson

Reputation: 52665

You can try below approach to open link in new window:

current_window = self.driver.current_window_handle
link = self.driver.find_element_by_tag_name('a')
href = link.get_attribute('href')
if href:
    self.driver.execute_script('window.open(arguments[0]);', href)
else:
    link.click()
new_window = [window for window in self.driver.window_handles if window != current_window][0]
self.driver.switch_to.window(new_window)
# Execute required operations
self.driver.close()
self.driver.switch_to.window(current_window)

This should allow you to get link URL and open it in new window with JavaScriptExecutor if it's not empty string and just click the link otherwise. As problematic link has attribute target="_blank" it will be opened in new window

Upvotes: 2

Related Questions