如何从<select> <option>获取值

时间:2015-05-11 21:26:27

标签: c# html-agility-pack

我试图从&lt; select&gt;中获取一些元素和&lt;选项&gt;元件。 这是我的代码: for(int td = 1; td&lt; = 1; td ++) {     使用(WebClient wc = new WebClient())     {         string pagina = wc.DownloadString(&#34; http://www.serebii.net/attackdex-xy/");         HtmlDocument doc = new HtmlDocument();         doc.LoadHtml(pagina);         串烟;         // var prova = doc.DocumentNode.SelectSingleNode(&#34; / html / body / table [2] / tr [2] / td [2] / div [2] / table / tr / td [1] / form /选择/选项&#34);         foreach(doc.DocumentNode.SelectNodes中的HtmlNode节点(String.Format(&#34; / html / body / table [2] / tr [2] / td [2] / font / div [2] / table / tr / td [{0}] / select / option&#34;,td)))         {             attacco = node.NextSibling.InnerText;             if(attacco!=&#34; AttackDex:A - G \ n&#34;&amp;&amp; attacco!=&#34; AttackDex:H - R \ n&#34;&amp;&amp; attacco!=&#34 ; AttackDex:S - Z \ n&#34;)             {                 var url = string.Format(&#34; http://www.serebii.net/attackdex-xy/ {0} .shtml&#34;,attacco.ToLower()。替换(&#34;&#34; ,&#34;&#34;));                 string attackPage = wc.DownloadString(url);                 HtmlDocument doc2 = new HtmlDocument();                 doc2.LoadHtml(attackPage);                 var category = doc.DocumentNode.SelectSingleNode(&#34; / html / body / table [2] / tr [2] / td [2]&#34;);             }         }     } } 这是html页面的代码: &lt; select name =&#34; SelectURL&#34;平变化=&#34; document.location.href = document.nav.SelectURL.options [document.nav.SelectURL.selectedIndex]。价值&#34;风格=&#34;颜色:#383838; font-size:8pt;背景:#CEBC77&#34;大小=&#34; 1&#34;&GT;  &lt; option&gt; AttackDex:A - G. &lt; / option&gt;&lt; option value =&#34; /attackdex-xy/absorb.shtml"&gt; Absorb&lt; / option&gt; &lt; option value =&#34; /attackdex-xy/acid.shtml"&gt; Acid&lt; / option&gt; &lt; option value =&#34; /attackdex-xy/acidarmor.shtml"&gt; Acid Armor&lt; / option&gt; &lt; option value =&#34; /attackdex-xy/acidspray.shtml"&gt; Acid Spray&lt; / option&gt; &lt; option value =&#34; /attackdex-xy/acrobatics.shtml"&gt; Acrobatics&lt; / option&gt; &lt; option value =&#34; /attackdex-xy/acupressure.shtml"&gt; Acupressure&lt; / option&gt; &lt; option value =&#34; /attackdex-xy/aerialace.shtml"&gt; Aerial Ace&lt; / option&gt; &lt; option value =&#34; /attackdex-xy/aeroblast.shtml"&gt; Aeroblast&lt; / option&gt; [...] 当我运行程序时,node(在foreach块中)的值为NULL。

1 个答案:

答案 0 :(得分:2)

我通过选择文档中的所有选项,然后过滤到具有名为“SelectURL”的祖先选择标记的选项来实现它。

doc.DocumentNode.SelectNodes("//option[ancestor::select[@name='SelectURL']]")