2024-04-26 10:20:45 发布
网友
from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Firefox() #do something if EC.alert_is_present: print "Alert Exists" driver.switch_to_alert().accept() print "Alert accepted" else: print "No alert exists"
有关例外条件的详细信息https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html
Python Webdriver脚本:
from selenium import webdriver browser = webdriver.Firefox() browser.get("http://sandbox.dev/alert.html") alert = browser.switch_to_alert() alert.accept() browser.close()
网页(alert.html):
<html><body> <script>alert("hey");</script> </body></html>
运行webdriver脚本将打开显示警报的HTML页面。Webdriver立即切换到警报并接受它。然后Webdriver关闭浏览器并结束。
如果您不确定是否会出现警报,那么您需要用类似这样的方法捕捉错误。
from selenium import webdriver browser = webdriver.Firefox() browser.get("http://sandbox.dev/no-alert.html") try: alert = browser.switch_to_alert() alert.accept() except: print "no alert to accept" browser.close()
如果需要检查警报文本,可以通过访问警报对象的文本属性来获取警报文本:
from selenium import webdriver browser = webdriver.Firefox() browser.get("http://sandbox.dev/alert.html") try: alert = browser.switch_to_alert() print alert.text alert.accept() except: print "no alert to accept" browser.close()
我使用的是Ruby绑定,但在Selenium Python bindings 2文档中发现: http://readthedocs.org/docs/selenium-python/en/latest/index.html
Selenium WebDriver内置了处理弹出对话框的支持。触发并执行打开弹出窗口的操作后,您可以使用以下命令访问警报:
alert = driver.switch_to_alert()
现在我想你可以这样做了:
if alert.text == 'A value you are looking for' alert.dismiss else alert.accept end
希望有帮助!
有关例外条件的详细信息https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html
Python Webdriver脚本:
网页(alert.html):
运行webdriver脚本将打开显示警报的HTML页面。Webdriver立即切换到警报并接受它。然后Webdriver关闭浏览器并结束。
如果您不确定是否会出现警报,那么您需要用类似这样的方法捕捉错误。
如果需要检查警报文本,可以通过访问警报对象的文本属性来获取警报文本:
我使用的是Ruby绑定,但在Selenium Python bindings 2文档中发现: http://readthedocs.org/docs/selenium-python/en/latest/index.html
Selenium WebDriver内置了处理弹出对话框的支持。触发并执行打开弹出窗口的操作后,您可以使用以下命令访问警报:
现在我想你可以这样做了:
希望有帮助!
相关问题 更多 >
编程相关推荐