我写了以下方法从网页中提取所需的html数据:
public async System.Threading.Tasks.Task<string> getdata()
{
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
HttpClient client = new HttpClient();
HtmlDocument document = new HtmlDocument();
byte[] htmlb = (await client.GetByteArrayAsync("http://<path-to-cgi>?passwd=" + (string)localSettings.Values["password"] + "&<param>=<hardcoded value>" + "&<param>=<hardcoded value>").ConfigureAwait(false));
document.LoadHtml(Encoding.UTF8.GetString(htmlb,0,htmlb.Length));
var inputs = document.DocumentNode.Descendants("div");
HtmlNode elm = null;
foreach (var input in inputs)
{
if (input.Attributes["id"].ToString() == "main")
{
elm = input;
}
}
return (elm.InnerHtml);
}
当我执行此方法时,我得到上面提到的异常。
答案 0 :(得分:0)
看起来你的if条件可能返回false,并且没有为elm
分配值。为了确保从函数返回值,请替换
return (elm.InnerHtml);
带
if(elm != null){
return (elm.InnerHtml ?? "");
}
else{
return "";
}