4

在 Selenium 2 中,该WebDriver对象仅提供了一种getPageSource()保存原始 HTML 页面的方法,而无需任何 CSS、JS、图像等。

有没有办法在 HTML 页面中保存所有引用的资源(类似于 HtmlUnit 的HtmlPage.save())?

4

3 回答 3

1

我知道我的答案已经很晚了,但是当我搜索自己时,我并没有真正找到这个问题的答案。所以我自己做了一些事情,希望我仍然可以帮助一些人。

对于 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.
    }
}

我确信它可以改进以包括任何不可预见的情况,但对于我的测试网站来说,它总是会像这样工作。

于 2015-12-31T13:01:11.163 回答
0

没有。如果可以,请执行HtmlUnit此特定任务。

我认为,你能做的最好的事情是Robot。同时按Ctrl+ S,用 确认Enter。它是盲目的,不完美的,但它是最接近你需要的东西。

于 2012-06-07T20:35:05.567 回答
0

您可以使用 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 就在那里。如果有人有办法解决这个问题,那就太棒了。

于 2014-01-17T19:26:44.260 回答