【发布时间】:2016-09-30 11:00:59
【问题描述】:
我很喜欢用 Python 处理警报。我最喜欢做的是:
- 打开一个网址
- 提交表单或点击一些链接
- 检查新页面是否出现警报
我使用 PhantomJS 使用 Javascript 制作了这个,但我什至会使用 Python 制作。
这里是javascript代码:
文件 test.js:
var webPage = require('webpage');
var page = webPage.create();
var url = 'http://localhost:8001/index.html'
page.onConsoleMessage = function (msg) {
console.log(msg);
}
page.open(url, function (status) {
page.evaluate(function () {
document.getElementById('myButton').click()
});
page.onConsoleMessage = function (msg) {
console.log(msg);
}
page.onAlert = function (msg) {
console.log('ALERT: ' + msg);
};
setTimeout(function () {
page.evaluate(function () {
console.log(document.documentElement.innerHTML)
});
phantom.exit();
}, 1000);
});
文件索引.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<form>
<input id="username" name="username" />
<button id="myButton" type="button" value="Page2">Go to Page2</button>
</form>
</body>
</html>
<script>
document.getElementById("myButton").onclick = function () {
location.href = "page2.html";
};
</script>
文件 page2.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8" />
</head>
<body onload="alert('hello')">
</body>
</html>
这行得通;它检测到 page2.html 上的警报。 现在我制作了这个 python 脚本:
test.py
import requests
from test import BasicTest
from selenium import webdriver
from bs4 import BeautifulSoup
url = 'http://localhost:8001/index.html'
def main():
#browser = webdriver.Firefox()
browser = webdriver.PhantomJS()
browser.get(url)
html_source = browser.page_source
#browser.quit()
soup = BeautifulSoup(html_source, "html.parser")
soup.prettify()
request = requests.get('http://localhost:8001/page2.html')
print request.text
#Handle Alert
if __name__ == "__main__":
main();
现在,如何使用 Python 检查 page2.html 上是否出现警报?首先我打开页面 index.html,然后打开 page2.html。 我才刚开始,所以任何建议都将不胜感激。
附言 我还测试了 webdriver.Firefox() 但它非常慢。 我也读过这个问题:Check if any alert exists using selenium with python
但它不起作用(下面是相同的先前脚本加上答案中建议的解决方案)。
.....
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
....
def main():
.....
#Handle Alert
try:
WebDriverWait(browser, 3).until(EC.alert_is_present(),
'Timed out waiting for PA creation ' +
'confirmation popup to appear.')
alert = browser.switch_to.alert()
alert.accept()
print "alert accepted"
except TimeoutException:
print "no alert"
if __name__ == "__main__":
main();
我得到了错误:
“selenium.common.exceptions.WebDriverException:消息:无效 命令方法..”
【问题讨论】:
标签: python selenium selenium-webdriver phantomjs alert