【发布时间】:2016-01-07 23:35:03
【问题描述】:
您好,我需要测试几个保存在 txt 文件中的 http 链接。逻辑如下:读取文本文件,解析html,分别读取以http://开头的每一行,并异步测试每一行。这是我到目前为止使用的代码,但没有任何反应。
private async void button4_Click(object sender, EventArgs e)
{
string text = System.IO.File.ReadAllText(@"C:\\Users\\Conal_Curran\\OneDrive\\C#\\MyProjects\\Web Crawler\\URLTester\\OP.htm");
MatchCollection matches = Regex.Matches(text, @"href=\""(.*?)\""");
if (matches.Count > 0)
{
List<Uri> uris = new List<Uri>();
foreach (Match m in matches)
{
string url = m.Groups["url"].Value;
Uri testUri = null;
if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out testUri))
{
uris.Add(testUri);
var lines = File.ReadLines(url);
foreach (var line in lines)
{
if (text.StartsWith("http://"))
{
var request = WebRequest.Create(text);
var response = (HttpWebResponse)await Task.Factory
.FromAsync<WebResponse>(request.BeginGetResponse,
request.EndGetResponse,
null);
Debug.Assert(response.StatusCode == HttpStatusCode.OK);
if (response == null)
{
BrokenLinks.Text = text;
label2.ForeColor = System.Drawing.Color.Red;
}
else
{
BrokenLinks.Text = "All URLS Are OK";
label2.ForeColor = System.Drawing.Color.Green;
}
}
else
{
MessageBox.Show("No URLS Selected");
}
}
}
}
}
}
除了使用正则表达式来挑选我尝试使用 htmlagilitypack 的 http 链接:
HtmlWeb hw = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc = hw.Load("C:\\Users\\Conal_Curran\\OneDrive\\C#\\MyProjects\\Web Crawler\\URLTester\\OP.htm");
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("url"))
{
// Get the value of the HREF attribute
string hrefValue = link.GetAttributeValue("href", "Saved!");
但是,我不断收到错误消息“对象引用未设置为对象的实例”。这发生在
foreach (doc.DocumentNode.SelectNodes("//a[@href]") 中的 HtmlNode 链接) {
【问题讨论】:
-
对于 HtmlAgilityPack,试试这个 var html = File.ReadAllText("C:\\Users\\Conal_Curran\\OneDrive\\C#\\MyProjects\\Web Crawler\\URLTester\\OP .htm"); HtmlAgilityPack.HtmlDocument 文档 = 新 HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(html);而 doc.DocumentNode.SelectNodes("//a") 代替
标签: c# asynchronous httpwebrequest httpwebresponse