Objective
System pop-up window This is a very common scene, sometimes it does not play out to operate, will throw an exception. Then do not know when it will come out, so long need to determine whether the pop-up window.
This article then Selenium2+python Automation 42-judging Element (expected_conditions) Expected_conditions this module
First, Judge alert source code Analysis
Class Alert_is_present (object):
"" "Expect an alert to be present." "" "
"" "to determine the current page of the Alert pop-up Window" "
def __init__ (self):
Pass
def __call__ (self, driver):
Try
Alert = Driver.switch_to.alert
Alert.text
Return alert
Except noalertpresentexception:
Return False
1. This class is relatively simple, there is no content in the initialization
2.__call__ inside is to judge if the text content of the popup is returned to the Alert object ( Note that this is not a return ture), it returns false if it is not retrieved.
Second, the instance operation
1. The previous procedure is optimized, in order to improve the stability of the script, to ensure that the elements appear after operation,
Here's how to combine webdriverwait: Selenium2+python Automation 38-Explicit Wait (webdriverwait)
2. The implementation steps are as follows, there are two types of results returned: return FALSE if not found; Return Alert object when found
3. First determine if alert pops up, if it pops up click OK button Accept ()
Third, reference code
# Coding:utf-8
From selenium import Webdriver
From Selenium.webdriver.common.action_chains import Actionchains
From Selenium.webdriver.support.select Import Select
From selenium.webdriver.support.wait import webdriverwait
From Selenium.webdriver.support import expected_conditions as EC
Driver = Webdriver. Firefox ()
url = "Https://www.baidu.com"
Driver.get (URL)
Mouse = webdriverwait (driver). Until (Lambda x:x.find_element ("link text", "Settings"))
Actionchains (Driver). Move_to_element (mouse). Perform ()
Webdriverwait (Driver). Until (Lambda x:x.find_element ("link text", "Search Settings"). Click ()
# Select Set Item
s = webdriverwait (driver, ten). Until (lambda x:x.find_element ("id", "NR"))
Select (s). Select_by_visible_text ("Show 50 per page")
# Click the Save button
JS = ' Document.getelementsbyclassname ("Prefpanelgo") [0].click (); '
Driver.execute_script (JS)
# to determine the results of the popup Exchange QQ Group: 232607095
result = Ec.alert_is_present () (driver)
If result:
Print Result.text
Result.accept ()
Else
Print "Alert does not eject! "
Selenium2+python Automation 47-judging pop-up box presence (alert_is_present) "Reprint"