通过 webdriver 单击 javascript 弹出窗口 [英] Click the javascript popup through webdriver

查看:26
本文介绍了通过 webdriver 单击 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).我不确定,如何通过 webdriver 点击弹出窗口.

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

如果需要查看alert的文本,可以通过访问alert对象的text属性获取alert的文本:

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

这篇关于通过 webdriver 单击 javascript 弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆