本文介绍了通过网络驱动程序单击JavaScript弹出窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Python中使用Selenium webdriver抓取一个网页

I am scraping a webpage using Selenium webdriver in Python

我正在处理的网页具有一个表单。我可以填写表格,然后单击提交按钮。

The webpage I am working on, has a form. I am able to fill the form and then I click on the Submit button.

它会生成一个弹出窗口(Javascript Alert)。我不确定如何通过网络驱动程序单击弹出窗口。

It generates an popup window( Javascript Alert). I am not sure, how to click the popup through webdriver.

任何想法怎么做?

谢谢

推荐答案

Python Webdriver脚本:

Python Webdriver Script:

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):

Webpage (alert.html):

<html><body>
    <script>alert("hey");</script>
</body></html>

运行webdriver脚本将打开显示警报的HTML页面。 Webdriver立即切换到警报并接受它。 Webdriver然后关闭浏览器并结束。

Running the webdriver script will open the HTML page that shows an alert. Webdriver immediately switches to the alert and accepts it. Webdriver then closes the browser and ends.

如果不确定是否会有警报,则需要使用类似的方法来捕获错误。

If you are not sure there will be an alert then you need to catch the error with something like this.

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()

如果需要要检查警报的文本,可以通过访问警报对象的text属性来获取警报的文本:

If you need to check the text of the alert, you can get the text of the alert by accessing the text attribute of the alert object:

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()

这篇关于通过网络驱动程序单击JavaScript弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 12:14