【问题标题】:How to save as web page in Selenium Webdriver Javascript?如何在 Selenium Webdriver Javascript 中保存为网页?
【发布时间】:2021-02-02 06:56:38
【问题描述】:
我正在尝试在 Selenium Webdriver JS (Firefox) 中使用 Ctrl+S 保存完整的网页。
我可以使用以下代码调用另存为对话框:
driver.findElement(webdriver.By.tagName('html')).sendKeys(Key.CONTROL + 's');
现在对话框出来了。但我不知道如何命名文件,也不知道如何回车。
有没有办法在 Selenium Webdriver JS 中执行此操作(与对话框交互),或者甚至绕过另存为对话框并将其保存到磁盘上?
非常感谢。
【问题讨论】:
标签:
javascript
selenium
selenium-webdriver
webdriver
【解决方案1】:
Selenium 不与本机对话框交互。您可以尝试解决此问题。
您可以将view-source 保存在文件中,而不是保存网页。
假设您要保存google.com 页面。
driver.get("view-source:http://www.google.com");
- 通过模拟
Ctrl+a和Ctrl+c这样选择页面的所有内容。
这是 dotnet 代码示例。你可以在 Js 中找到类似的东西。
Actions action = new Actions(driver);
action.KeyDown(Keys.LeftControl)
.SendKeys("a")
.SendKeys("c")
.Build()
.Perform();
string source = Clipboard.GetText(TextDataFormat.UnicodeText);
File.WriteAllText(@"PathToSaveTheSource", source);
【解决方案2】:
这是一个Java语言的演示:
/* 1. get current web page source which is the complete html */
String pageHtmlSource = driver.getPageSource();
// you will get things like this:
// <html>
// <head>
// ...
// </head>
// <body>
// ...
// </body>
// </html>
/* 2. then save the String into a file */
请注意,driver.getPageSource() 和 Ctrl+s 之间存在一些差异。 driver.getPageSource() 只获取 html 源码,而 Ctrl+s 也可以保存 js/css。
【解决方案3】:
替代解决方案:
“另存为”对话框无法通过 Selenium 进行交互(您需要一些外部程序)。我使用require('child_process').exec() 运行一个.bat 文件来运行一个发送密钥的.vbs 脚本。
您可以通过为 chromedriver 提供默认下载目录来绕过“另存为”对话框:#setDownloadPath。
我还没有看到 Firefox 的替代品。
遗憾的是,这段模拟“Ctrl”+S 的代码对我不起作用:
driver.findElement(webdriver.By.tagName('html')).sendKeys(Key.CONTROL + 's');