在 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.
}
}
我确信它可以改进以包含任何不可预见的情况,但对于我的测试网站来说,它总是会像这样工作。
您可以使用 selenium 交互来处理它。
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 也会遇到在发送密钥后没有返回任何内容的问题,因此 Try Catches 就是为了解决这个问题而设计的。如果有人有办法解决这个问题,那就太棒了。
请参阅我的答案此处,将网页保存为单个 MHTML 文件(html + 独立文件中的所有资源)