0
我想在C#中使用HTML敏捷包來獲取每個<li>
文字和鏈接的價值,我還需要從每個<li>
鏈接ABC的網頁<div>
和<h1>
null值異常.COM/one.html,abc.com/two.html & abc.com/three.htmlC#和HTML敏捷性包:在嵌套的foreach循環
我在運行時收到此錯誤:
System.ArgumentNullException:值不能爲空。
[ArgumentNullException: Value cannot be null. Parameter name: second]
System.Linq.Enumerable.Zip(IEnumerable`1 first, IEnumerable`1 second, Func`3 resultSelector) +2619657
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +95
System.Web.UI.Control.LoadRecursive() +59
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +678
HTML
<ul>
<li>ListOne<a href="abc.com/one.html"></a></li>
<li>ListTwo<a href="abc.com/two.html"></a></li>
<li>ListThree<a href="abc.com/three.html"></a></li>
</ul>
C#
string Url = "WebAddress1";
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(Url);
foreach (var item in doc.DocumentNode.SelectNodes("//*[@id=\"pageContent\"]/ul[1]/li").Zip(doc.DocumentNode.SelectNodes("//*[@id=\"pageContent\"]/ul[1]/li/a"), (a, b) => new { A = a, B = b }))
{
var a = item.A;
var b = item.B;
ListBox1.Items.Add(a.InnerText);
ListBox2.Items.Add(b.GetAttributeValue("href", ""));
string Url2 = "WebAddress1" + b.GetAttributeValue("href", "");
HtmlWeb web2 = new HtmlWeb();
HtmlDocument doc2 = web2.Load(Url2);
foreach (var item2 in doc2.DocumentNode.SelectNodes("//*[@id=\"pageContent\"]/article/div[4]/div[1]").Zip(doc2.DocumentNode.SelectNodes("//*[@id=\"pageContent\"]/article/h1"), (c, d) => new { C = c, D = d }))
{
var c = item2.C;
var d = item2.D;
ListBox3.Items.Add(c.InnerText);
ListBox4.Items.Add(d.InnerText);
}
}
*注:此代碼使用XPath網頁的某些元素:abc.com/one .html,abc.com/two.html and abc.com/three.html
您是否嘗試調試過?例外說你Zip方法的參數是NULL,不支持。 –
'doc2.DocumentNode.SelectNodes(「// * [@ id = \」pageContent \「]/article/h1」)'提取'article'元素的'h1'元素與您指定的'id',並且不存在一個。 –
如果我把第二個'foreach'循環放在第一個'foreach'循環的旁邊,並在'Url2'中提供相同的鏈接,那麼它的工作。只有當我使用嵌套的'foreach'循環時纔會出現異常。 此外,上面的嵌套代碼只與導航欄的xPath一起工作 – Shady