C#访问网页的办法很多,一般使用WebClient、WebBrowser或者HttpWebRequest。前两种比较简单,后者功能更多,方便我们伪造访问痕迹。
下面是HttpWebRequest带cookies访问百度首页的方法,访问结果如下图所示:
从上图红线框中可以看出,带上cookies可以达到模拟登陆的效果,顺便模拟了浏览器,下面是C#代码。
/// <summary> /// 获取页面html /// </summary> /// <param name="uri">访问url</param> /// <param name="refererUri">来源url</param> /// <param name="encodingName">编码名称 例如:gb2312</param> /// <returns></returns> public string Get(string uri, string refererUri, string encodingName) { string html = string.Empty; CookieContainer cookieContainer = new CookieContainer(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); cookieContainer.Add(new Cookie("BAIDUID", "67017F5C6A5EE8351192F7D34E7A221E:FG=1", "", "www.baidu.com")); cookieContainer.Add(new Cookie("PSTM", "1523879243", "", "www.baidu.com")); cookieContainer.Add(new Cookie("BIDUPSID", "A29EA919049CED566C183C7ED175C6AB", "", "www.baidu.com")); cookieContainer.Add(new Cookie("BD_UPN", "1a314353", "", "www.baidu.com")); cookieContainer.Add(new Cookie("BDUSS", "1F4Wk1EUUxEWkNEZS1lUWdSNkFWOW5IbThoYXNYcktMWmhmRkE5MkxvQU9Jd0piQVFBQUFBJCQAAAAAAAAAAAEAAAD9qTIYw867wzGw19K5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA6W2loOltpaY", "", "www.baidu.com")); request.ContentType = "text/html;charset=" + encodingName; request.Method = "Get"; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.5221.400 QQBrowser/10.0.1125.400"; request.CookieContainer = cookieContainer; if (!string.IsNullOrEmpty(refererUri)) request.Referer = refererUri; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream streamResponse = response.GetResponseStream()) { using (StreamReader streamResponseReader = new StreamReader(streamResponse, Encoding.GetEncoding(encodingName))) { html = streamResponseReader.ReadToEnd(); } } } return html; }
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/241276.html