WebClient下载字符串与WebBrowser View源不同
我正在创建一个C#4.0应用程序来使用Web客户端下载网页内容。
WebClientfunction
public static string GetDocText(string url) { string html = string.Empty; try { using (ConfigurableWebClient client = new ConfigurableWebClient()) { /* Set timeout for webclient */ client.Timeout = 600000; /* Build url */ Uri innUri = null; if (!url.StartsWith("http://")) url = "http://" + url; Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out innUri); try { client.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR " + "3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.2; AskTbFXTV5/5.15.4.23821; BRI/2)"); client.Headers.Add("Vary", "Accept-Encoding"); client.Encoding = Encoding.UTF8; html = client.DownloadString(innUri); if (html.Contains("Pagina non disponibile")) { string str = "site blocked"; str = ""; } if (string.IsNullOrEmpty(html)) { return string.Empty; } else { return html; } } catch (Exception ex) { return ""; } finally { client.Dispose(); } } } catch (Exception ex) { return ""; } } public class ConfigurableWebClient : WebClient { public int? Timeout { get; set; } public int? ConnectionLimit { get; set; } protected override WebRequest GetWebRequest(Uri address) { var baseRequest = base.GetWebRequest(address); var webRequest = baseRequest as HttpWebRequest; if (webRequest == null) return baseRequest; if (Timeout.HasValue) webRequest.Timeout = Timeout.Value; if (ConnectionLimit.HasValue) webRequest.ServicePoint.ConnectionLimit = ConnectionLimit.Value; return webRequest; } }
我检查了C#Web客户端中的下载内容,它与浏览器略有不同
内容。 我在浏览器(Mozilla Firefox)和我的Web客户端function中提供相同的URL。
网页正确显示内容,但我的Web客户端DownloadString返回另一个
HTML。 请参阅下面的Web客户端响应。
Webclient下载了html
#d__fFH{position:absolute;top:-5000px;left:-5000px}#d__fF{font-family:serif;font-size:200px;visibility:hidden}#glance7ca96c1b,#hiredf795fe70,#target01a7c05a,#hiredf795fe70{display:none!important}
我的问题是我的Webclientfunction没有返回实际的网页内容。
请帮忙。
某些Web程序通过HTTP请求标头响应不同。
所以,如果你想要与网络浏览器相同的HTML,
那么您将发送相同的HTTP请求您的Web浏览器!
怎么样?
使用Firefox Developer工具或Chrome Developer Tool,并复制HTTP请求!