我在C#中将Selenium与Chromedriver结合使用:
<packages>
<package id="Selenium.Chrome.WebDriver" version="2.42" targetFramework="net461" />
<package id="Selenium.WebDriver" version="3.14.0" targetFramework="net461" />
</packages>
打开包含警报的网页时,我总是会遇到异常:
unexpected alert open: {Alert text : muh}
(Session info: chrome=69.0.3497.100)
(Driver info: chromedriver=2.42.591088 (7b2b2dca23cca0862f674758c9a3933e685c27d5),platform=Windows NT 10.0.17134 x86_64)
示例代码:
static void Main(string[] args) {
ChromeOptions options = new ChromeOptions();
options.UnhandledPromptBehavior = UnhandledPromptBehavior.Dismiss;
using (var browser = new ChromeDriver(options)) {
browser.Navigate().GoToUrl(@"D:\downloads\test.html");
Console.WriteLine(browser.PageSource); //Exception happens here
}
Console.WriteLine("done");
Console.ReadLine();
}
示例HTML:
<!doctype html>
<html>
<head>
</head>
<body>
<script>
alert("muh");
document.write("<p>blah</p>");
</script>
</body>
</html>
看来options.UnhandledPromptBehavior = UnhandledPromptBehavior.Dismiss
没什么区别。我应该怎么做才能防止这种情况发生?
答案 0 :(得分:0)
尝试通过try / catch解决问题:
try
{
Console.WriteLine(browser.PageSource); //Exception happens here
}
catch (UnhandledAlertException unhandledAlertException)
{
// ignore exception or put the rest of the code
}