如何从中获取价值<SELECT><OPTION>

c# html-agility-pack

我正在尝试从<select><option>元素中获取一些元素。

这是我的代码:

for(int td = 1; td <= 1; td++)
{
    using (WebClient wc = new WebClient())
    {
        string pagina = wc.DownloadString("http://www.serebii.net/attackdex-xy/");
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(pagina);

        string attacco;
        //var prova = doc.DocumentNode.SelectSingleNode("/html/body/table[2]/tr[2]/td[2]/div[2]/table/tr/td[1]/form/select/option");

        foreach (HtmlNode node in doc.DocumentNode.SelectNodes(String.Format("/html/body/table[2]/tr[2]/td[2]/font/div[2]/table/tr/td[{0}]/select/option", td)))
        {
            attacco = node.NextSibling.InnerText;

            if(attacco != "AttackDex: A - G\n" && attacco != "AttackDex: H - R\n" && attacco != "AttackDex: S - Z\n")
            {
                var url = string.Format("http://www.serebii.net/attackdex-xy/{0}.shtml", attacco.ToLower().Replace(" ", ""));
                string attackPage = wc.DownloadString(url);
                HtmlDocument doc2 = new HtmlDocument();
                doc2.LoadHtml(attackPage);

                var category = doc.DocumentNode.SelectSingleNode("/html/body/table[2]/tr[2]/td[2]");
            }
        }
    }
}

这是html页面的代码:

for(int td = 1; td <= 1; td++)
{
    using (WebClient wc = new WebClient())
    {
        string pagina = wc.DownloadString("http://www.serebii.net/attackdex-xy/");
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(pagina);

        string attacco;
        //var prova = doc.DocumentNode.SelectSingleNode("/html/body/table[2]/tr[2]/td[2]/div[2]/table/tr/td[1]/form/select/option");

        foreach (HtmlNode node in doc.DocumentNode.SelectNodes(String.Format("/html/body/table[2]/tr[2]/td[2]/font/div[2]/table/tr/td[{0}]/select/option", td)))
        {
            attacco = node.NextSibling.InnerText;

            if(attacco != "AttackDex: A - G\n" && attacco != "AttackDex: H - R\n" && attacco != "AttackDex: S - Z\n")
            {
                var url = string.Format("http://www.serebii.net/attackdex-xy/{0}.shtml", attacco.ToLower().Replace(" ", ""));
                string attackPage = wc.DownloadString(url);
                HtmlDocument doc2 = new HtmlDocument();
                doc2.LoadHtml(attackPage);

                var category = doc.DocumentNode.SelectSingleNode("/html/body/table[2]/tr[2]/td[2]");
            }
        }
    }
}

当我运行程序时,node(在foreach块中)的值为NULL。

热门答案

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

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



许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因