Selenium2+Python automation-handling browser pop-ups (reproduced)

We often encounter various kinds of pop-up windows when browsing the web. When doing UI automation testing, it is necessary to deal with these pop-up windows. Here, we will introduce the two methods of handling pop-up windows in the front-end world.

1. The alert pop  -up
alert popup 
window is the simplest one. Selenium has its own method to deal with it. Use switch_to.alert to locate the pop-up window first, and then use a series of methods to operate:

  • accept - Click the [Confirm] button
  • dismiss - Click the [Cancel] button (if there is a button)
  • send_keys - input content (if there is an input box)

Here is an example from a rookie tutorial: http://www.runoob.com/try/try.php?filename=tryjs_alert , click [Show Alert Box] on the left side of the page and an alert pop-up window will pop up: 
example

We can use the following code to achieve the effect of switching to the pop-up window and clicking the [OK] button:

al = driver.switch_to_alert()
al.accept()

The switch_to_alert() here is actually the old way of writing. It should be used switch_to.alert(), but the new way of writing will report an error. At present, it is guessed that it is a version problem, and the new way of writing may not be supported. Here, the old way of writing is used first.

The following is the complete code. In order to see clearly when running, I added two waits:

# encoding:utf-8
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("http://www.runoob.com/try/try.php?filename=tryjs_alert")
driver.switch_to.frame("iframeResult") driver.find_element_by_xpath("html/body/input").click() time.sleep(1) al = driver.switch_to_alert() time.sleep(1) al.accept()

2. Custom pop-up window 
Because the alert pop-up window is not beautiful, most websites now use custom pop-up windows, which cannot be controlled by using the method that comes with Selenium. At this time, JS Dafa must be moved out. Here is an example of the homepage of the official website of New World Education: As 
New World Education Official Website Home
you can see, the pop-up window in the picture is the mainstream form of expression. To deal with this kind of pop-up window, you can use the HTML DOM Style object, which has a display attribute, which can set the element How to be displayed, please refer to http://www.w3school.com.cn/jsref/prop_style_display.asp for detailed explanation . Set the value of display to none to remove this popup:

js = 'document.getElementById("doyoo_monitor").style.display="none";'

The complete code is as follows:

# encoding:utf-8

from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.get("http://sh.xsjedu.org/") time.sleep(1) js = 'document.getElementById("doyoo_monitor").style.display="none";' driver.execute_script(js)

Is it simple and efficient?

Guess you like

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