Selenium2+python automation 29-js handles multi-window

foreword

When opening the link on the page, another window often pops up (the multi-window situation is explained in the previous article: Selenium2+python automation 13-multi-window, handle ), so it is more complicated to switch back and forth between multiple windows , then is there a way to make the newly opened link open in a window?

To solve this problem, you have to find the reason from the html source code, and then modify the element attributes to solve it. Obviously js is omnipotent in this regard, so this article has to rely on the omnipotent js brother.

1. Multi-window situation

    1. When hitting the baidu website link, a window will be reopened

    (Note: My Baidu page is logged in, and the window will not be reopened when not logged in)

 

2. View element attributes: target=" _blank"

1. Looking at the element attributes, you will find that these links have a common attribute: target=" _blank"

3. Remove the target=" _blank" attribute

1. Because this link element target=" _blank", a tab will be reopened when the link is opened, so to solve this problem, just remove this attribute.

2. In order to verify this problem, you can switch to the html editing interface and manually remove the " _blank" attribute

3. After deleting the " _blank" attribute, reopen the link, and you will find that the new link will be opened in the original tab.

Fourth, js remove the target=" _blank" attribute

1. In the first step, in order to log in first, I will load the configuration file here without logging in (if you won't read this: Selenium2+python automation 18-loading Firefox configuration )

2. The positioning method of js is used here to locate the class attribute of the element

3. After locating the element, directly modify the target attribute value to be empty

5. Reference code

# coding:utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# 加载配置文件免登录
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/")

# 修改元素的target属性
js = 'document.getElementsByClassName("mnav")[0].target="";'
driver.execute_script(js)
driver.find_element_by_link_text("糯米").click()

 

Note: Not all links are applicable to this method, this article is only applicable to links with this target=" _blank" attribute

This article only provides solutions and ideas to solve the problem, don't copy the code completely! ! !

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325454610&siteId=291194637
Recommended