Objective
When you open a link on the page, often pop-up another window (multi-window case in front of this is explained: Selenium2+python Automation 13-Multi-window, handle (handle)), so it is more complicated to switch back and forth between multiple windows, So is there a way to open the newly opened link in a window?
To solve this problem, we have to find the reason from the HTML source and then modify the element properties to solve it. Obviously JS in this respect is omnipotent, so this article has to rely on the almighty JS Big Brother.
One, multi-window situation
1. When you link to Baidu's website, a window will open again
(Note: My Baidu page is logged in, no login will not reopen the window)
Second, view element properties:target= "_blank"
1. Viewing element properties, you will find that these links have a common property:target= "_blank"
Third, remove the target= "_blank" attribute
1. Because this link element target= "_blank", so open the link will reopen a tab, then solve this problem, remove the attribute is OK.
2. In order to verify this problem, you can switch to the HTML editing interface, manually remove the "_blank" property
3. After deleting the "_blank" property, reopen the link, and you will find that the new link opens in the Original tab.
Four, JS remove target= "_blank" attribute
1. The first step in order to log in first, I am here to load the configuration file is free of login (not see this: Selenium2+python Automation 18-load Firefox configuration)
2. Use the JS positioning method to locate the element's class attribute
3. Directly modify the target property value to null after locating the element
V. Reference code
# Coding:utf-8
From selenium import Webdriver
From Selenium.webdriver.common.keys import keys
Import time
# Load Profile Free Login
Profiledir = R ' C:\Users\Gloria\AppData\Roaming\Mozilla\Firefox\Profiles\1x41j9of.default '
Profile = Webdriver. Firefoxprofile (Profiledir)
Driver = Webdriver. Firefox (Profile)
Driver.get ("https://www.baidu.com/")
# Modify the target property of an element
JS = ' Document.getelementsbyclassname ("Mnav") [0].target= "";
Driver.execute_script (JS)
Driver.find_element_by_link_text ("glutinous rice"). Click ()
Note: Not all links are applicable to this method, this article only applies to this target= "_blank" attribute link condition
This article only provides solutions and ideas to solve the problem, do not copy the code completely!!!
Selenium2+python Automated 29-JS Processing multiple windows