我正在尝试构建一个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属性。通过扩展此范围,我想知道最有效的方法是将其包括在内。
href元素的
<a>属性
href元素的
<link>属性
src元素的
<script>属性
src元素的
<img>属性
action元素的
<form>属性
还有其他人能想到的吗?
可以通过使用Monster xpath一次调用
SelectNodes来找到它们,还是多次调用SelectNode并遍历每个集合更有效?
请您参考如下方法:
以下应该工作:
SelectNodes("//*[@href or @src or @action]")
然后必须修改下面的
if语句。

