【问题标题】:Why HttpWebRequest returns significantly different html source comparing to chrome > view page source?与 chrome > 查看页面源相比,为什么 HttpWebRequest 返回显着不同的 html 源?
【发布时间】:2020-08-09 01:34:37
【问题描述】:

我需要获得尽可能接近 chrome 或其他浏览器的正常页面视图源的 HTML 源代码。但是下面的代码为相同的 URL 返回不同的代码。

String url = @"https://m.facebook.com";
try
{
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
   HttpWebResponse response = (HttpWebResponse)request.GetResponse();
   if (response.StatusCode == HttpStatusCode.OK)
   {
      Stream receiveStream = response.GetResponseStream();
      StreamReader readStream = null;
      if (response.CharacterSet == null)
         readStream = new StreamReader(receiveStream);
      else
         readStream = new StreamReader(receiveStream,
                     Encoding.GetEncoding(response.CharacterSet.Replace("\"", string.Empty)));
      //readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
      string data = readStream.ReadToEnd();
      response.Close();
      readStream.Close();
      //string[] sps = data.Split(new string[] { @"videoId"":""" }, StringSplitOptions.RemoveEmptyEntries);
   }
}
catch (Exception ex)
{}

返回如下:

<!DOCTYPE html>
<html lang="en" id="facebook" class="no_js">
<head><meta charset="utf-8" /><meta name="referrer" content="default" id="meta_referrer" /><script nonce="EW2LyNr7">window._cstart=+new Date();</script><script nonce="EW2LyNr7">function envFlush(a){function b(b){for(var c in a)b[c]=a[c]}window.requireLazy?window.requireLazy(["Env"],b):(window.Env=window.Env||{},b(window.Env))}envFlush...

但是浏览器源是..

<!DOCTYPE html><html><head><script id="u_0_2" nonce="db1veTby">"use strict";window.MPageLoadClientMetrics=function(){var a=+new Date(),b={prelude_onload:["jewels_visible","first_paint","visibility_change","tti"],nav_started:["first_paint","visibility_change","prelude_onload"],first_paint:["jewels_visible","visibility_change","prelude_onload"],jewels_visible:["tti","visibility_change","navigation","prelude_onload"],tti:["e2e","visibility_change","navigation"]},c=3,d=3,e="nav_started",f=!0,g="",h="",i=1,j="",k="",l="",m=function(){},n=!0,o=!1,p=!1,q=[],r=window.performance||window.msPerformance||window.webkitPerformance||{},s=(window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||window.setTimeout).bind(window),t=window.location.origin||window.location.protocol+"//"+window.location.hostname+(window.location.port&&":"+window.location.port);function u(b,c,d,e,f,i){r.timing&&r.timing.navigationStart&&(a=r.timing.navigationStart),j=b,k=c,l=d,g=e,h=f,n=i,x()}function v(a){var c=b[e];return c&&c.indexOf(a)!==-1}function w(a){return!b[a]}function x(){var a,b;do

如何获得类似的代码来查看chrome的页面源代码?

【问题讨论】:

  • 您在第一个 blob 中看到的是“您的浏览器与 facebook 不兼容,因为您没有 Javascript 功能”消息。这是有道理的,因为您使用套接字以编程方式直接从网站拉取,仅此而已(参见类名no_js?)。一旦该站点检测到 Javascript,它很可能会发送一堆代码来呈现 facebook 的真实页面(第二个 blob)。这就是为什么网络爬虫现在构建在知道如何运行 javascript 和呈现页面的浏览器之上的原因。不过只是猜测。我可能是错的。
  • @Andy 感谢您的回复。有没有办法在不实际使用浏览器的情况下进行类似于浏览器请求的请求?
  • 不知道——我知道您可以使用 C# 来处理由浏览器呈现的网页的某些框架...其中一个框架名为 selenium 但是,我更多地考虑自动化测试。
  • 这个问题刚刚出现在 SO:stackoverflow.com/questions/63322012/… 这个人正在使用 selenium 来抓取网站(尽管验证码有问题),所以我猜人们 确实 使用它那:)
  • 我在几个月前也尝试过 selenium,但我记得它对于在许多不同环境和设置上运行的解决方案并不可靠。

标签: c# html google-chrome httpwebrequest


【解决方案1】:

Facebook 要求User-Agent 正确显示页面,否则它会重定向到/unsupportedbrowser 页面。

这里是使用HttpClient的例子

class Program
{
    private static readonly HttpClient client = new HttpClient();

    static async Task Main(string[] args)
    {
        client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36");

        string result = await client.GetStringAsync("https://m.facebook.com");
        Console.WriteLine(result);
        Console.ReadKey();
    }
}

输出与谷歌浏览器完全相同。

【讨论】:

  • 找不到 HttpClient 的参考,甚至没有为我列出 Microsoft.Net.Http 参考。我使用.Net 4.00。如何解决这个问题?
  • @nawala 您至少需要 .NET Framework 4.5,但建议使用 4.6(或更高版本)。你为什么用4.0? Windows XP 支持?
  • @nawala 考虑this answer。请记住,Windows XP 是卡在古老的 4.0 中的唯一原因。 Win7甚至x86 fluenty都支持4.6-4.8。
  • 非常感谢@aepot。我将你的答案标记为答案,但是你让我明白了找到让我的代码工作的方法。我会尝试用 HttpWebRequest 来解决这个问题。我在我的项目中使用 VS2010,所以还有另一个限制的理由。
  • 是的,我也想买一个更新的版本。再次感谢
猜你喜欢
  • 2015-01-02
  • 1970-01-01
  • 2016-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-14
  • 2020-09-15
  • 1970-01-01
相关资源
最近更新 更多