我正在抓取网页,直到现在我还在使用 ArgumentNullException
捕获 try/catch
。但是,我想将逻辑更改为使用 if
。我的尝试在下面。
if (document.DocumentNode.SelectNodes("//td")
.Where(x => x.Attributes["title"].Value.Contains("Log.html")).Any() is true) {
HtmlNode[] nodes = document.DocumentNode.SelectNodes("//td")
.Where(x => x.Attributes["title"].Value.Contains("Log.html")).ToArray();
if (nodes.Length > 1) {
nodes = nodes.Where((source, index) => index != 1).ToArray();
}
[..........]
} else {
LogException("Item is null", taskId, buildId);
}
但是上线了:
<块引用>if (document.DocumentNode.SelectNodes("//td") .Where(x => x.Attributes["title"].Value.Contains("Log.html")).Any() 为真)
我仍然收到 ArgumentNullException
。我该怎么写呢?
答案 0 :(得分:1)
您也可以使用 XPath 表达式来检查属性内容:
var logs=document.DocumentNode
.SelectNodes("//td[contains(@title,'Log.html')]")
.ToArray();
if (logs.Length==0)
{
LogException("Item is null", taskId, buildId);
}
else if (logs.Length>1)
{
logs=logs[1..];
}
C#8 中的新范围语法允许替换
nodes.Where((source, index) => index != 1).ToArray();
只要
logs=logs[1..];
答案 1 :(得分:-2)
为什么不
.Where(x => {
if (x.Attributes["title"] != null) {
return x.Attributes["title"].Value.Contains("Log.html")).Any();
}
else {
return false;
}
})
答案 2 :(得分:-2)
一种方法可能是:
var nodes = document.DocumentNode.SelectNodes("//td");
if (nodes.Any())
{
var logs = nodes.Where(x => x.Attributes["title"].Value.Contains("Log.html"));
if(logs.Any())
{
var filterLogs = logs.Where((source, index) => index != 1).ToArray();
}
}
另一个选项取决于您的 C# 版本,它使用可选链 null Null Conditional operator
var result = document.DocumentNode?.SelectNodes("//td")?
.Where(x => x.Attributes["title"].Value?.Contains("Log.html"))