[英]How to save as web page in Selenium Webdriver Javascript?
I am trying to save a complete webpage using Ctrl+S in Selenium Webdriver JS (Firefox).我正在尝试在 Selenium Webdriver JS (Firefox) 中使用 Ctrl+S 保存完整的网页。 I can call out the save as dialog using this code:
我可以使用以下代码调出另存为对话框:
driver.findElement(webdriver.By.tagName('html')).sendKeys(Key.CONTROL + 's');
Now the dialog is out.现在对话框出来了。 But I dont know how to name the file nor how to hit the enter.
但我不知道如何命名文件,也不知道如何按下回车键。 Is there anyway to do this (interact with the dialog) in Selenium Webdriver JS or maybe even bypass the save as dialog and just save it onto the disk?
无论如何在Selenium Webdriver JS中执行此操作(与对话框交互),或者甚至绕过另存为对话框并将其保存到磁盘上?
Thank you very much.非常感谢。
Selenium does not interact with native dialogs. Selenium 不与本机对话框交互。 You can try a workaround for this.
您可以尝试解决此问题。
Instead of saving the web page, you can save the view-source
in a file.您可以将
view-source
保存在文件中,而不是保存网页。
Let's say you want to save google.com
page.假设您想保存
google.com
页面。
view-source
like so.view-source
url。 driver.get("view-source:http://www.google.com");
Ctrl+a
and Ctrl+c
like so.Ctrl+a
和Ctrl+c
选择页面的所有内容。 This is dotnet code example.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);
This is a demo in Java language:这是 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 */
Note that there are some differences between driver.getPageSource()
and Ctrl+s
.请注意,
driver.getPageSource()
和Ctrl+s
之间存在一些差异。 driver.getPageSource()
only gets the html source, while Ctrl+s
can also saves js/css. driver.getPageSource()
只获取html源码, Ctrl+s
也可以保存js/css。
Alternate Solution:替代解决方案:
The "Save As" dialog cannot be interacted with via Selenium (you need some external program). “另存为”对话框无法通过 Selenium 进行交互(您需要一些外部程序)。 I use
require('child_process').exec()
to run a .bat file to run a .vbs script that sends keys.我使用
require('child_process').exec()
运行 .bat 文件来运行发送密钥的 .vbs 脚本。
You can bypass the "Save As" dialog by giving a default download directory to chromedriver: #setDownloadPath .您可以通过为 chromedriver 提供默认下载目录来绕过“另存为”对话框: #setDownloadPath 。
I have not seen a firefox alternative for this.我还没有看到 Firefox 替代品。
Sadly, this code to simulate "Ctrl" + S is not working for me:可悲的是,这个模拟“Ctrl”+ S的代码对我不起作用:
driver.findElement(webdriver.By.tagName('html')).sendKeys(Key.CONTROL + 's');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.