我在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:downloadstest.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
没有任何区别。我应该怎么做才能防止这种行为?
尝试用 try/catch 来解决它:
try
{
Console.WriteLine(browser.PageSource); //Exception happens here
}
catch (UnhandledAlertException unhandledAlertException)
{
// ignore exception or put the rest of the code
}