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()
trang web (alert.html):
<html><body>
<script>alert("hey");</script>
</body></html>
Chạy kịch bản webdriver sẽ mở ra trang HTML cho thấy một cảnh báo. Webdriver ngay lập tức chuyển sang cảnh báo và chấp nhận nó. Trình quản lý web sau đó đóng trình duyệt và kết thúc.
Nếu bạn không chắc chắn sẽ có một cảnh báo thì bạn cần phải nắm bắt lỗi với một cái gì đó như thế này.
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()
Nếu bạn cần phải kiểm tra nội dung của cảnh báo, bạn có thể nhận được văn bản của các cảnh báo bằng cách truy cập các thuộc tính văn bản của đối tượng cảnh báo:
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()
Nguồn
2012-05-29 18:44:15
Xem http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_Does_WebDriver_support_Javascript_alerts_and_prompts?Nó không phải Python, nhưng tôi nghĩ nó khá dễ hiểu. – rubik
Ya. Nhưng nó không hoạt động với Python. Tôi đã không thể tìm thấy một hàm tương đương để xử lý cửa sổ bật lên. – Kiran
bản sao có thể có của [Cách nhấp và xác minh sự tồn tại của cửa sổ bật lên (cảnh báo)] (http://stackoverflow.com/questions/3084850/how-to-click-and-verify-the-existence-of-a -pop-up-alert) – Acorn