通过Webdriver点击JavaScript弹出框

20

我正在使用Python的Selenium webdriver来爬取一个网页。

这个网页有一个表单,我可以填写表单并点击提交按钮。

之后会弹出一个JavaScript Alert窗口,但我不确定如何通过webdriver来点击这个窗口。

您有什么想法吗?

谢谢!


请参阅http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_Does_WebDriver_support_Javascript_alerts_and_prompts? 这不是Python,但我认为它相当易懂。 - rubik
是的。但它不能在Python中使用。我还没有找到一个等效的函数来处理弹出窗口。 - Kiran
2
好的,不是这样的。我的问题与 Webdriver 相关,而你所提到的问题涉及 Selenium。 - Kiran
6个回答

27

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

4
switch_to_alert()在最新的Selenium Python绑定版本2.46.0中已不再使用,请改用driver.switch_to.alert。来源:http://selenium-python.readthedocs.org/en/latest/api.html - SpartaSixZero

4
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"

关于excepted_conditions更多信息,请查看此链接


1
@bad_deadpool,感谢您的更新!另外,那个链接是404错误--该文档现在位于http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.switch_to_alert。 - Greg Sadetsky

2
如果您想接受或点击弹出窗口,不管它是为了什么,那么请执行以下操作。
alert.accept

alertselenium.webdriver.common.alert.Alert(driver) 类的对象,而 accept 是该对象的方法。

源码


1
我正在使用Ruby绑定,但下面是我在Selenium Python绑定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

希望能对你有所帮助!


1
请尝试以下代码!对我来说很好用!
alert = driver.switch_to.alert
try:
   alert.accept() #If you want to Accept the Alert
except:
   alert.dismiss()  #If  You want to Dismiss the Alert.

1
太棒了!这帮了我很多!谢谢朋友 :) - Bryan_C

0

这取决于处理表单提交的JavaScript函数,如果没有这样的函数,请尝试使用POST提交表单


我得到了一个简单的JavaScript警告,显示“感谢提交”,我想按回车键关闭弹出窗口。 - Kiran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接