Home > Blockchain >  target __blank doesn't change page source and current url in Selenium
target __blank doesn't change page source and current url in Selenium

Time:11-10

I use Selenium with Python to extract some data from a website. My question is simple, I click on a link which opens with target="__blank", and the problem is that I want to get the current URL of the just opened page. Unfortunately, neither the page URL is changed, nor the page source. I found that changing the element attribute to target="__self" does the trick. However, I don't see this trick quite often when I searched around the Internet and that leads me to the question is that the only way?

CodePudding user response:

target="_blank"

Opens the requested URL in a new Tab/Window. Seleniums only focusses on the current window, so the newly opened window won't be focussed by Selenium. Thats why

target="_self"

works as intended, as it changes the current window.

See target behaviour here: https://wiki.selfhtml.org/wiki/HTML/Attribute/target

CodePudding user response:

Usually another approach is used.
After opening a link in a new tab you can get the list of all tabs:

tabs = driver.window_handles

And then you can use this list to navigate between the tabs. If you want to go to the second tab you need this code:

driver.switch_to.window(tabs[1])

If you want to return to the first tab you can use this:

driver.switch_to.window(tabs[0])

Also after opening a link in a new tab you can switch to the new window using the official example:

original_tab = driver.current_window_handle
for tab in driver.window_handles:
        if tab != original_tab:
            driver.switch_to.window(tab)
            break

But I myself use the approach I wrote first (the one with tabs[1] ).

  • Related