在Selenium 2中,WebDriver
对象只提供了一个方法getPageSource()
,该方法保存原始HTML页面,没有任何CSS,JS,图像等。
有没有办法将所有引用的资源也保存在HTML页面中(类似于HtmlUnit的HtmlPage.save()
)?
我的答案迟到了,但是当我自己搜索时,我并没有真正找到这个问题的答案。所以我自己做了一些事情,希望我还能帮助一些人。
对于 c#,这是我是如何做到的:
using system.net;
string DataDirectory = "C:\Temp\AutoTest\Data\";
string PageSourceHTML = Driver.PageSource;
string[] StringSeparators = new string[] { "<" };
string[] Result = PageSourceHTML.Split(StringSeparators, StringSplitOptions.None);
string CSSFile;
string FileName = "filename.html";
System.IO.File.WriteAllText(DataDirectory + FileName, PageSourceHTML);
foreach(string S in Result)
{
if(S.Contains("stylesheet"))
{
CSSFile = S.Substring(28); // strip off "link rel="stylesheet" href="
CSSFile = CSSFile.Substring(0,CSSFile.Length-10); // strip off characters behind, like " />" and newline, spaces until next "<" was found. Can and probably will be different in your case.
System.IO.Directory.CreateDirectory(DataDirectory + "\" + CSSFile.Substring(0, CSSFile.LastIndexOf("/"))); //create the CSS direcotry structure
var Client = new WebClient();
Client.DownloadFile(Browser.Browser.WebUrl + "/" + CSSFile, DataDirectory + "\" + CSSFile); // download the file and save it with the same filename under the same relative path.
}
}
我相信它可以改进以包含任何不可预见的情况,但对于我的测试网站,它将始终像这样工作。
不。如果可以,请为这项特定任务选择HtmlUnit
。
我认为,你能做的最好的事情就是Robot
。按 按Ctrl + S 同时,用回车确认。它是盲目的,它是不完美的,但它是最接近你需求的东西。
您可以使用硒相互作用来处理它。
using OpenQA.Selenium.Interactions;
也有几种方法可以做到这一点。我处理此类事情的方法之一是找到页面中心的项目,或者您希望保存的任何区域,然后执行操作构建器。
var htmlElement = driver.FindElement(By.XPath("//your path"));
Actions action = new Actions(driver);
try
{
action.MoveToElement(htmlElement).ContextClick(htmlElement).SendKeys("p").Build().Perform();
}
catch(WebDriverException){}
这将简单地右键单击该区域,然后在右键单击时发送键"p",这是Firefox中的"将页面另存为"热键。另一种方法是让构建器发送密钥。
var htmlElement = driver.FindElement(By.Xpath("//your path"));
action.MoveToElement(htmlElement);
try
{
action.KeyDown(Keys.Control).SendKeys("S").KeyUp(Keys.Control).Build().Perform();
}
catch(WebDriverException){}
请注意,在这两种情况下,如果您离开驱动程序的范围,例如Windows窗体,则必须切换大小写/代码以在弹出Windows窗体时处理它。发送密钥后,Selenium 也会遇到任何返回的问题,因此尝试捕获就在那里。 如果有人有办法解决这个问题,那就太棒了。