Selenium2+python automation-window multi-label processing method summary (reproduced)

This article is transferred from the blog: Shanghai - Little T

Original address: https://i.cnblogs.com/EditArticles.aspx?opt=1

When we use Selenium to encounter multiple browser windows or multiple tabs (Tab) in a single browser, it is often not easy to handle. Here are two processing methods.

The example cited in this article is Baidu. There is a hyperlink at the bottom of Baidu's homepage that says "Set Baidu as the homepage". Clicking on it will open a new tab, which is a good example: 

 

1、switch_to.window()

This method is a built-in method in Webdriver. In addition to being used for switching in multiple browsers, this method can also be used to switch between multiple tabs (Tabs) in a single browser. The idea is to first obtain the handles of all tabs, and then Loop through and determine whether it is the current tab page, if not, switch. The detailed code is as follows:

# encoding:utf-8

 

from selenium import webdriver

 

driver = webdriver.Firefox()

driver.get("http://www.baidu.com")

driver.find_element_by_id("setf").click()

handles = driver.window_handles

for handle in handles:

    if driver.current_window_handle != handle:

        driver.switch_to.window(handle)

driver.find_element_by_link_text("Baidu Homepage").click()

In the last sentence, clicking the "Baidu Home" link on the new tab successfully means that the tab has been successfully switched.

2. Use JS to clear the target value

Use the F12 tool to view the hyperlink, you can see that there is a target attribute:



target=_blank means to open the linked document in a new window (quoted from w3school), the popular explanation is that the hyperlink will be opened in a new window (new tab), then clearing its value can realize that the hyperlink will not be clicked after clicking the hyperlink. A new tab will open. Use the Document object method to find the id and clear the value of its target:

js = 'document.getElementById("setf").target="";'

After the JS is written, execute it to achieve the effect. The complete code is as follows:

# encoding:utf-8

 

from selenium import webdriver

 

driver = webdriver.Firefox()

driver.get("http://www.baidu.com")

js = 'document.getElementById("setf").target="";'

driver.execute_script(js)

driver.find_element_by_id("setf").click()

driver.find_element_by_link_text("Baidu Homepage").click()

In the last sentence, clicking the "Baidu Home" link on the new tab successfully means that the tab has been successfully switched.

HTML DOM defines a variety of methods for finding elements, in addition to getElementById(), there are getElementsByName() and getElementsByTagName(), which are detailed at http://www.w3school.com.cn/jsref/dom_obj_document.asp usage.

Guess you like

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