如何加载没有URL的html源代码

本文关键字:URL html 源代码 何加载 加载 | 更新日期: 2023-09-27 18:00:40

我已经编写了使用HtmlAgilityPack获取给定URL的id和xpath的代码。我想使用该代码,但我想在其上使用的网站只有一个URL。基本上,网站中的内容会发生变化,但URL不会。所以我可以访问我想访问的所有页面,但如果不使用C#中的URL,如何下载该页面的HTML源代码?

internal Dictionary<string, string> GetIDsAndXPaths(string url)
{
    var web = new HtmlWeb();
    var webidsAndXPaths = new Dictionary<string, string>();
    var doc = web.Load(url);
    var nodes = doc.DocumentNode.SelectNodes("//*[@id]");
    if (nodes == null) return webidsAndXPaths;
    // more code to get ids and such
    return webidsAndXPaths;
}

如何加载没有URL的html源代码

您可以使用WebDriver来导航要获取页面源的页面。一旦WebDriver出现在页面上,您只需要让WebDriver下载页面源。将页面源传递到web。通过名为"page"的变量加载。

internal Dictionary<string, string> GetIDsAndXPaths()
{
    var web = new HtmlWeb();
    var webidsAndXPaths = new Dictionary<string, string>();
    var page = driver.PageSource; // Gets the source of the page last loaded by the browser
    const string path = @"C:'temp'myHtml.html";
    var sw = new StreamWriter(path, false);
    sw.Write(page);
    sw.Close();
    const string url = path;
    var doc = web.Load(page);
    var nodes = doc.DocumentNode.SelectNodes("//*[@id]");
    if (nodes == null) return webidsAndXPaths;
    // more code to get ids and such
    return webidsAndXPaths;
}