c# HTML敏捷包与IF语句
本文关键字:IF 语句 HTML | 更新日期: 2023-09-27 18:14:27
我有这段代码,我需要运行一个if语句来设置变量的值。问题是,当第一个条件为空时,它就失败了。有人能告诉我我做错了什么吗?
IF语句在foreach循环中,每次迭代向列表中添加一个值。
非常感谢!
string result = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
using (var stream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(new StringReader(result));
HtmlNode root = doc.DocumentNode;
string itemdesc = doc.DocumentNode.SelectSingleNode("//h1[@class='producttitle']").InnerText;
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='resultsset']/table/tbody[@class='result']/tr");
List<string> sellers = new List<string>();
List<string> prices = new List<string>();
foreach (HtmlNode node in nodes)
{
string seller = string.Empty;
if(node.SelectSingleNode(".//ul[@class='sellerInformation']/img").GetAttributeValue("alt", string.Empty) != null)
{
seller = node.SelectSingleNode(".//ul[@class='sellerInformation']/img").GetAttributeValue("alt", string.Empty);
}
else if (node.SelectSingleNode(".//ul[@class='sellerInformation']/a/img").GetAttributeValue("alt", string.Empty) != null)
{
seller = node.SelectSingleNode(".//ul[@class='sellerInformation']/a/img").GetAttributeValue("alt", string.Empty);
}
else
{
seller = node.SelectSingleNode(".//ul[@class='sellerInformation']/li/div/span/a/b").InnerText;
}
sellers.Add(seller);
string price = node.SelectSingleNode(".//span[@class='price']").InnerText;
prices.Add(price);
}
可能SelectSingleNode
返回null,因此对GetAttributeValue
的调用是空引用问题。检查属性前需要先检查SelectSingleNode
的结果