HtmlAgility Pack get single node get null value



我正在尝试获取具有XPath的单个节点,但是我在节点上获得了空值,不知道为什么

        WebClient wc = new WebClient();
        string nodeValue;
        string htmlCode = wc.DownloadString("http://www.freeproxylists.net/fr/?c=&pt=&pr=&a%5B%5D=0&a%5B%5D=1&a%5B%5D=2&u=50");
        HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
        html.LoadHtml(htmlCode);
        HtmlNode node = html.DocumentNode.SelectSingleNode("//table[@class='DataGrid']/tbody/tr[@class='Odd']/td/a");
        nodeValue = (node.InnerHtml);
与您

尝试从中获取信息的 html 相比,我在您的 xpath 中看到至少 2 个错误。

  1. 没有具有作为祖先。
  2. 即使你的Xpath工作了,那么你也只能得到一个
  3. 因为你已经决定选择SingleNode而不是SelectNodes 。

看起来他们正在对您要做的事情进行某种懒惰的保护。由于 a 标签只是用 IPDecode 中括起来的十六进制表示。所以提取链接真的没有问题。但你至少可以做的是在发布之前查看html。你显然根本没有尝试过。由于您从当前代码中获取的html不是您提供给我们的链接的<正文> - 这意味着您必须从绝对URL获取html页面或仅使用Selenium。

但是由于我是一个膨胀的人,我将使用Xpath,Html Agility Pack和Selenium为您制作整个解决方案。以下解决方案获取网站的 html。然后仅读取具有 class="Odd" 的

。之后,它会找到所有"加密"并将它们解码为字符串并将它们写入数组。之后,有一个关于如何从一个定位点获取属性值的小示例。
    private void HtmlParser(string url)
    {
        HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
        htmlDoc.OptionFixNestedTags=true;
        GetHTML(url);
        htmlDoc.Load("x.html", Encoding.ASCII, true);      
        HtmlNodeCollection nodes = htmlDoc.DocumentNode.SelectNodes("//table[@class='DataGrid']/descendant::*/tr[@class='Odd']/td/script");
        List<string> urls = new List<string>();
        foreach(HtmlNode x in nodes)
        {
            urls.Add(ConvertStringToUrl(x.InnerText));
        }
        Console.WriteLine(ReadingTheAnchor(urls[0]));
    }
    private string ConvertStringToUrl(string octUrl)
    {
        octUrl = octUrl.Replace("IPDecode("", "");
        octUrl = octUrl.Remove(octUrl.Length -2);
        octUrl = octUrl.Replace("%", "");
        string ascii = string.Empty;
        for (int i = 0; i < octUrl.Length; i += 2)
        {
            String hs = string.Empty;
            hs   = octUrl.Substring(i,2);
            uint decval =   System.Convert.ToUInt32(hs, 16);
            char character = System.Convert.ToChar(decval);
            ascii += character;
        }
        //Now you get the <a> containing the links. which all can be read as seperate html files containing just a <a>
        Console.WriteLine(ascii);
        return ascii;
    }
    private string ReadingTheAnchor(string anchor)
    {
        //returns url of anchor
        HtmlDocument anchorHtml = new HtmlAgilityPack.HtmlDocument();
        anchorHtml.LoadHtml(anchor);
        HtmlNode h = anchorHtml.DocumentNode.SelectSingleNode("a");
        return h.GetAttributeValue("href", "");
    }
    //using OpenQA.Selenium; using OpenQA.Selenium.Firefox;
    private void GetHTML(string url)
    {
        using (var driver = new FirefoxDriver())
        {
            driver.Navigate().GoToUrl(url);
            Console.Clear();
            System.IO.File.WriteAllText("x.html", driver.PageSource);
        }
    }

最新更新