问题描述
我在 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 弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!