【问题标题】:Using WebClient to load HTML使用 WebClient 加载 HTML
【发布时间】:2012-08-25 10:47:43
【问题描述】:

我正在尝试下载网页:

string remoteUri = "http://whois.domaintools.com/94.100.179.159";
WebClient myWebClient = new WebClient();
byte[] myDataBuffer = myWebClient.DownloadData(remoteUri);
string download = Encoding.ASCII.GetString(myDataBuffer);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(download);
doc.Save("file1.htm");

有错误

webexception 未处理:(403) Forbidden。

还有其他方法可以下载页面吗? 我试过 HtmlDocument 类,但我可以看到它需要在浏览器中加载网页。

HtmlWeb hwObject = new HtmlWeb();
        string ip = "http://whois.domaintools.com/";
        HtmlAgilityPack.HtmlDocument htmldocObject = hwObject.Load(ip);

        foreach (HtmlNode link in htmldocObject.DocumentNode.SelectNodes("//meta[@name = 'description']"))
        {
            ...
        }

【问题讨论】:

    标签: c# webclient html-agility-pack


    【解决方案1】:
    using (var myWebClient = new WebClient())
    {
        myWebClient.Headers["User-Agent"] = "MOZILLA/5.0 (WINDOWS NT 6.1; WOW64) APPLEWEBKIT/537.1 (KHTML, LIKE GECKO) CHROME/21.0.1180.75 SAFARI/537.1";
    
        string page = myWebClient.DownloadString("http://whois.domaintools.com/94.100.179.159");
    
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(page);
    }
    

    【讨论】:

    • 我用过这个用户代理,但仍然禁止错误 - Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1"跨度>
    • @fen1ksss 只需复制并粘贴上面的代码。我在发布之前尝试过......并再次对其进行了测试。它有效。
    • 不,还是一样...我正在使用windows xp的虚拟机,mb这是关键吗?我有 mac os 10.7
    • 例如适用于 www.google.com,但我之前的代码也适用于 google..
    • myWebClient.Credentials = new NetworkCredential(...)。也可以试试myWebClient.Proxy=null
    【解决方案2】:

    当网站在请求中找不到任何用户代理时,网站只是返回一个错误,这是工作代码。

    string remoteUri = "http://whois.domaintools.com/94.100.179.159";
    HtmlDocument doc = new HtmlDocument();
    using (WebClient myWebClient = new WebClient())
    {
      myWebClient.Headers.Add(HttpRequestHeader.UserAgent, "some browser user agent");
      doc.Load(myWebClient.OpenRead(remoteUri));
    }
    doc.Save("file1.htm");
    

    或者如果你想使用HtmlWeb

    HtmlWeb hwObject = new HtmlWeb();
    hwObject.UserAgent = "some browser user agent";
    //more code...
    

    【讨论】:

    • 我使用了这个用户代理,但仍然禁止错误 - Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1"跨度>
    猜你喜欢
    • 1970-01-01
    • 2021-08-14
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    相关资源
    最近更新 更多