2012-01-05 32 views
1

我想构建一个ASP.NET页面,它可以抓取网页并正确显示它们,并将所有相关的html元素编辑为在适当的位置包含绝对URL。ASP.NET Web页面镜像,用绝对路径替换所有相对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属性。通过扩展这个我想知道什么是最有效的方法将包括;

  • href<a>元件
  • 属性
  • href属性为<link>元件
  • src属性为<script>
  • 元件
  • src属性为<img>元件
  • action属性为<form>元件

还有其他人可以想到的吗?

这些可以通过使用一个怪物xpath对SelectNodes进行单次调用找到,还是多次调用SelectNode并通过每个集合都会更有效率?

回答

3

下面应该工作:

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

,然后你不得不去适应下if声明。

+0

谢谢,不得不将它更改为'SelectNodes(“// * [@ href或@src或@action]”)'来选择任何东西。这是最有效的解决方案吗? – 2012-01-05 12:49:30

+0

对不起,这就是我的意思,哎呀。效率将取决于某些因素,如文档的大小和结构。如果您知道文档的特定部分没有任何链接,那么您可以将这些内容加入到xpath中,甚至将xpath分解为小型查询。 – Digbyswift 2012-01-05 13:26:41