我正在解析http链接的网页,首先解析出所有锚定标签,然后解析出href标签,然后运行正则表达式以删除所有非独立链接的标签(如href =“/ img / link .PHP“)。以下代码正常工作,但在解析的链接之间还附加了许多空行。
while (parse.ParseNext("a", out tag))
{
string value;
//A REGEX value, this one finds proper http address'
Regex regexObj = new Regex(@"^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$");
if (tag.Attributes.TryGetValue("href", out value))
{
string value2;
//Start finding matches...
Match matchResults = regexObj.Match(value);
value2 = matchResults.Value;
lstPages.AppendText(value2 + "\r\n");
}
}
为了解决这个问题,我添加了以下代码,它可以清理列表:
if (value2 != "")
{
lstPages.AppendText(value2 + "\r\n");
}
然而,我
!= ""
行的来源。 我的实际问题是关于这两个问题,但更多关于问题#2,因为我想知道为什么我会收到这些结果,但是如果有更有效的方法。
答案 0 :(得分:2)
static void Main(string[] args)
{
var html = new HtmlDocument();
var request = WebRequest.Create("http://stackoverflow.com/questions/6256982/parsing-links-and-recieving-extra-blanks/6257328#6257328") as HttpWebRequest;
using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
{
html.Load(responseStream);
}
foreach (var absoluteHref in html.DocumentNode.SelectNodes("//a[starts-with(@href, 'http')]"))
{
Console.WriteLine(absoluteHref.Attributes["href"].Value);
}
}
答案 1 :(得分:2)
如果正则表达式无法匹配,则value2
中获取空字符串的原因是matchResults.Value == ""
。您可以直接检查value2 != ""
以查看正则表达式是否匹配,而不是检查是否matchResults.Success
。无论如何,你基本上都是这样做的,因为你的特定正则表达式永远不会匹配空字符串,但检查matchResults.Success
会更直接。
要考虑的另一件事是,没有必要在循环的每次迭代中创建Regex对象。以下是我建议的修改:
//A REGEX value, this one finds proper http address'
Regex regexObj = new Regex(@"^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$");
while (parse.ParseNext("a", out tag))
{
string value;
if (tag.Attributes.TryGetValue("href", out value))
{
string value2;
//Start finding matches...
Match matchResult = regexObj.Match(value);
if (matchResult.Success)
{
value2 = matchResult.Value;
lstPages.AppendText(value2 + "\r\n");
}
}
}
答案 2 :(得分:-1)
TryGetValue
是一种通用方法(Type T
)。如果它没有任何返回值,则返回default value of the type
,String.Empty
或""
表示字符串