为什么 SelectSingleNode 导致每个站点 System.NullReferenceException

Why is SelectSingleNode Causing a System.NullReferenceException for Every Site

我只是想弄清楚 C# 中的网页抓取。现在我正在尝试通过 HTTP GET API 调用检索用户的外部 IP。我尝试了多个不同的站点,并且所有站点都具有相同的 System.NullReferenceException。这是我的代码:

using System;
using HtmlAgilityPack;

namespace Tracer
{
    class IPTracer
    {
        static void Main(string[] args)
        {
            scrape(@"http://api.ipify.org/");
        }

        static void scrape(string url)
        {
            HtmlWeb scraper = new HtmlWeb();
            HtmlDocument html = scraper.Load(url);

            string ip = html.DocumentNode.SelectSingleNode("/html/body/pre").InnerText;
            Console.WriteLine(ip);
        }
    }
}

这可能是一个非常简单的错误,因为我是 C# 的新手,但这已经困扰我好几天了,我还没有找到解决方案。不,我检查过,“html”本身不为空。

当我查看浏览器开发工具中的元素部分时,我还看到 html 的 XPath 为 /html/body/pre。但看起来浏览器开发工具在撒谎,因为当你查看 http://api.ipify.org/ return 的页面源代码时,你会发现它没有 return 任何 html - 它只是 return 访问者的 ip 地址作为文本。

鉴于没有 HTML 可解析,您不需要 HtmlAgilityPack(并且可能无法使用)用于此网站。 您可以像这样使用 HttpClient returns 获取文本:

using System;
using System.Net.Http;

namespace Tracer
{
    class IPTracer
    {
        static HttpClient client = new HttpClient();


        static void Main(string[] args)
        {
            scrape(@"http://api.ipify.org/");
        }

        static void scrape(string url)
        {
            string ip = "";
            using (HttpResponseMessage response = client.GetAsync(url).Result)
            {
                using (HttpContent content = response.Content)
                {
                    ip =  content.ReadAsStringAsync().Result;
                }
            }

            Console.WriteLine(ip);
        }
    }
}