【问题标题】:ASP.NET Web Page Mirror, Replacing all relative URLs with absolute PathsASP.NET 网页镜像,用绝对路径替换所有相对 URL
【发布时间】:2012-01-05 12:15:46
【问题描述】:

我正在尝试构建一个 ASP.NET 页面,该页面可以抓取网页并正确显示它们,所有相关的 html 元素都经过编辑,在适当的地方包含绝对 URL。

这个问题已经部分回答在这里https://stackoverflow.com/a/2719712/696638

结合使用上面的答案和这篇博文http://blog.abodit.com/2010/03/a-simple-web-crawler-in-c-using-htmlagilitypack/,我构建了以下内容;

public partial class Crawler : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
        Response.Clear();

        string url = Request.QueryString["path"];

        WebClient client = new WebClient();
        byte[] requestHTML = client.DownloadData(url);
        string sourceHTML = new UTF8Encoding().GetString(requestHTML);

        HtmlDocument htmlDoc = new HtmlDocument();
        htmlDoc.LoadHtml(sourceHTML);

        foreach (HtmlNode link in htmlDoc.DocumentNode.SelectNodes("//a[@href]")) {
            if (!string.IsNullOrEmpty(link.Attributes["href"].Value)) {
                HtmlAttribute att = link.Attributes["href"];
                string href = att.Value;

                // ignore javascript on buttons using a tags
                if (href.StartsWith("javascript", StringComparison.InvariantCultureIgnoreCase)) continue;

                Uri urlNext = new Uri(href, UriKind.RelativeOrAbsolute);
                if (!urlNext.IsAbsoluteUri) {
                    urlNext = new Uri(new Uri(url), urlNext);
                    att.Value = urlNext.ToString();
                }
            }
        }

        Response.Write(htmlDoc.DocumentNode.OuterHtml);

    }
}

这只替换链接的 href 属性。通过扩展它,我想知道最有效的方法是包含什么;

  • <a> 元素的 href 属性
  • <link> 元素的 href 属性
  • <script> 元素的 src 属性
  • <img> 元素的 src 属性
  • <form> 元素的 action 属性

还有其他人能想到的吗?

是否可以使用带有怪物 xpath 的单个调用 SelectNodes 来找到这些,还是多次调用 SelectNodes 并遍历每个集合会更有效?

【问题讨论】:

    标签: c# asp.net xpath html-agility-pack


    【解决方案1】:

    以下应该有效:

    SelectNodes("//*[@href or @src or @action]")
    

    然后你必须修改下面的if 语句。

    【讨论】:

    • 谢谢,必须将其更改为 SelectNodes("//*[@href or @src or @action]") 才能选择任何内容。这是最有效的解决方案吗?
    • 对不起,这就是我的意思,哎呀。效率将取决于某些因素,例如文档的大小和结构。如果您知道文档的某些特定部分没有任何链接,那么您可以将这些部分处理到您的 xpath 中,甚至将 xpath 分解为小查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多