【发布时间】: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