通过webdriver点击javascript弹窗
我正在用Python的Selenium webdriver抓取一个网页。
这个网页上有一个表单。我可以填写这个表单,然后点击提交按钮。
这时会弹出一个窗口(JavaScript警告)。我不太确定怎么通过webdriver点击这个弹出的窗口。
有没有什么办法可以做到呢?
谢谢!
6 个回答
2
如果你想要接受或者点击弹出的窗口,不管它是什么内容的话,
alert.accept
这里的alert
是一个对象,它属于selenium.webdriver.common.alert.Alert(driver)
这个类,而accept
是这个对象的方法。
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”的更多信息可以在这里找到:https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html
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()