目录:信息采集入门系列目录

下面记录的是我自己整理的C#请求页面核心类,主要有如下几个方法

1.HttpWebRequest Get请求获得页面html

2.HttpWebRequest Post请求获得页面html

3.模拟登录获得cookie内容

4.模拟登录获得cookie字符串

5.代理的设置

6.利用webbrowser 获取js生成的页面

7.为webbrowser设置cookie,模拟登录

8.使用demo

HttpWebRequest Get请求获得页面html

注意点:以前抓取觉得很慢,最后发现是代理的问题,没有代理就设置为null,这样就不用每次去找代理,影响执行效率,还有一些参数可以自习设置,比如模拟浏览器等。

        /// <summary>
/// get请求获得页面的html
/// </summary>
/// <param name="url">需要获取的url</param>
/// <param name="proxy">代理,没有设置为null,不然每次去读代理造成请求很慢</param>
/// <param name="cookie">该网站所需要的cookie</param>
/// <param name="timeout">超时时间</param>
/// <returns>页面请求后的html</returns>
public static string Crawl(string url, WebProxy proxy, CookieContainer cookie, int timeout = )
{
string result = string.Empty;
HttpWebRequest request = null;
WebResponse response = null;
StreamReader streamReader = null;
try
{
request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Proxy = proxy;
request.Timeout = timeout;
request.AllowAutoRedirect = true;
request.CookieContainer = cookie;
response = (HttpWebResponse)request.GetResponse();
streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = streamReader.ReadToEnd(); }
catch (Exception ex)
{
throw ex;
}
finally
{
if (request != null)
{
request.Abort();
}
if (response != null)
{
response.Close();
}
if (streamReader != null)
{
streamReader.Dispose();
}
} return result;
}

HttpWebRequest Post请求获得页面html

        /// <summary>
/// post请求获得页面
/// </summary>
/// <param name="url">需要获取的url</param>
/// <param name="postdata">post的数据字符串,如id=1&name=test</param>
/// <param name="proxy">代理</param>
/// <param name="cookie">coolie</param>
/// <param name="timeout">超时</param>
/// <returns></returns>
public static string Crawl(string url, string postdata,WebProxy proxy, CookieContainer cookie, int timeout = )
{
string result = string.Empty;
HttpWebRequest request = null;
WebResponse response = null;
StreamReader streamReader = null;
try
{
request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Proxy = proxy;
request.Timeout = timeout;
request.AllowAutoRedirect = true;
request.CookieContainer = cookie; byte[] bs = Encoding.ASCII.GetBytes(postdata);
string responseData = String.Empty;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bs.Length;
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, , bs.Length);
reqStream.Close();
}
response = (HttpWebResponse)request.GetResponse();
streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = streamReader.ReadToEnd(); }
catch (Exception ex)
{
throw ex;
}
finally
{
if (request != null)
{
request.Abort();
}
if (response != null)
{
response.Close();
}
if (streamReader != null)
{
streamReader.Dispose();
}
} return result;
}

模拟登录获得cookie内容

先找到登录的页面,分析登录页面的post参数和链接,获得cookie后可以直接传到上面的方法

        /// <summary>
///根据模拟请求页面获得cookie
/// </summary>
/// <param name="url">模拟的url</param>
/// <returns>cookie</returns>
public static CookieContainer GetCookie(string url, WebProxy proxy, int timeout = )
{
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
CookieContainer cc = new CookieContainer();
request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Proxy = proxy;
request.Timeout = timeout;
request.AllowAutoRedirect = true;
request.CookieContainer = cc;
response = (HttpWebResponse)request.GetResponse();
response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
return cc;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (request != null)
{
request.Abort();
}
if (response != null)
{
response.Close();
}
} }

模拟登录获得cookie字符串

        /// <summary>
/// 获得cookie字符串,webbrowser可以使用
/// </summary>
/// <param name="url"></param>
/// <param name="proxy"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public static string GetCookieString(string url, WebProxy proxy, int timeout = )
{
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
CookieContainer cc = new CookieContainer();
request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Proxy = proxy;
request.Timeout = timeout;
request.AllowAutoRedirect = true;
request.CookieContainer = cc;
response = (HttpWebResponse)request.GetResponse();
response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
string strcrook = request.CookieContainer.GetCookieHeader(request.RequestUri);
return strcrook; }
catch (Exception ex)
{
throw ex;
}
finally
{
if (request != null)
{
request.Abort();
}
if (response != null)
{
response.Close();
}
}
}

代理的设置

       /// <summary>
/// 创建代理
/// </summary>
/// <param name="port">代理端口</param>
/// <param name="user">用户名</param>
/// <param name="password">密码</param>
/// <returns></returns>
public static WebProxy CreatePorxy(string port, string user, string password)
{
WebProxy proxy = new WebProxy();
proxy.Address = new Uri(port);
proxy.Credentials = new NetworkCredential(user, password);
return proxy;
}

利用webbrowser 获取js生成的页面

说明:由于不知道页面什么时候执行完成,这里是等待5s,默认执行完成,效率有待提高。

另外执行需要线程安全添加[STAThread]

        /// <summary>
/// 抓取js生成的页面
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string CrawlDynamic(string url)
{
WebBrowser browser = new WebBrowser(); browser.ScriptErrorsSuppressed = true; browser.Navigate(url); //先要等待加载完毕
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
} System.Timers.Timer timer = new System.Timers.Timer(); var isComplete = false; timer.Elapsed += new System.Timers.ElapsedEventHandler((sender, e) =>
{
//加载完毕
isComplete = true; timer.Stop();
}); timer.Interval = * ; timer.Start(); //继续等待 5s,等待js加载完
while (!isComplete)
Application.DoEvents(); var htmldocument = browser.Document;
return htmldocument.ActiveElement.InnerHtml;
}

为webbrowser设置cookie,模拟登录

刚开始始终不成功以为这个方法不能用,后面发现原来是doain设置有问题,我的例子是www.aa.xxx.com,设置的为http://xx.com可以使用,这个地方可能需要根据自己的情况来选择域名。

        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData); /// <summary>
/// 为webbrowser设置cookie
/// </summary>
/// <param name="cookieStr">cookie字符串,可以从上面方法获得</param>
/// <param name="domain">需要设置的域名</param>
public static void SetCookie(string cookieStr,string domain)
{
foreach (string c in cookieStr.Split(';'))
{
string[] item = c.Split('=');
if (item.Length == )
{
string name = item[];
string value = item[];
InternetSetCookie(domain, name, value);
} }
}

使用demo

            //代理,没有就直接传null
WebProxy proxy = WebCrawl.WebRequestHelper.CreatePorxy("xx.com", "user", "password"); //根据登录页得到cookie
CookieContainer cookie = WebCrawl.WebRequestHelper.GetCookie("http://xxxx.login.com", proxy); //获取页面
string html = WebCrawl.WebRequestHelper.Crawl("http://xxx.index.com", proxy, cookie); //根据登录页得到cookie字符串
string cookiestr = WebCrawl.WebRequestHelper.GetCookieString("http://xxxx.login.com", proxy); //为webbrowser设置cookie
WebCrawl.WebRequestHelper.SetCookie(cookiestr, "https://xx.com"); //获取需要登录切用js生成的页面,当然普通页面也可以
string htmlWithJs = WebCrawl.WebRequestHelper.CrawlDynamic("http://xxx.index.com");

C#获取网页信息核心方法(入门一)的更多相关文章

  1. C# HttpWebRequest 绝技 根据URL地址获取网页信息

    如果要使用中间的方法的话,可以访问我的帮助类完全免费开源:C# HttpHelper,帮助类,真正的Httprequest请求时无视编码,无视证书,无视Cookie,网页抓取 1.第一招,根据URL地 ...

  2. 使用URLConnection获取网页信息的基本流程

    参考自core java v2, chapter3 Networking. 注:URLConnection的子类HttpURLConnection被广泛用于Android网络客户端编程,它与apach ...

  3. PHP版微信第三方实现一键登录及获取用户信息的方法

    本文实例讲述了PHP版微信第三方实现一键登录及获取用户信息的方法.分享给大家供大家参考,具体如下: 注意,要使用微信在第三方网页登录是需要“服务号”才可以哦,所以必须到官方申请. 一开始你需要进入微信 ...

  4. 使用URLConnection获取网页信息的基本流程 分类: H1_ANDROID 2013-10-12 23:51 3646人阅读 评论(0) 收藏

    参考自core java v2, chapter3 Networking. 注:URLConnection的子类HttpURLConnection被广泛用于Android网络客户端编程,它与apach ...

  5. JS获取网页宽高方法集合

    JS获取网页宽高等方法的集合:document.body.clientWidth - 网页可见区域宽document.body.clientHeight - 网页可见区域高 document.body ...

  6. 在php中分别使用curl的post提交数据的方法和get获取网页数据的方法

    在php中分别使用curl的post提交数据的方法和get获取网页数据的方法整理分享一下额,具体代码如下: (1)使用php curl获取网页数据的方法: $ch=curl_init(); //设置选 ...

  7. Oracle 和 SQLSERVER 重新获取统计信息的方法

    1. Oracle 重新获取统计信息的命令 exec dbms_stats.gather_schema_stats(ownname =>) # 需要修改 ownername options 指定 ...

  8. JavaScript获取浏览器信息的方法

    Window有navigator对象让我们得知浏览器的全部信息.我们可以利用一系列的API函数得知浏览器的信息. JavaScript代码如下: ? 1 2 3 4 5 6 7 8 9 10 11 1 ...

  9. C#获取网页信息并存入数据库

    1,获取以及商品分类信息 给一网页获取网页上商品信息的分类 using Skay.WebBot; using System; using System.Collections.Generic; usi ...

随机推荐

  1. Ubuntu16.04+Cuda8.0+1080ti+caffe+免OpenCV3.2.0+faster-rCNN教程

    一.事先声明:1.Ubuntu版本:Ubuntu使用的是16.04.而不是16.04.1或16.04.2,这三个是有区别的.笔者曾有过这样的经历,Git上一个SLAM地图构建程序在Ubuntu14.0 ...

  2. XSS攻击处理方案

    1. XSS攻击基本概念 XSS是一种经常出现在web应用中的计算机安全漏洞,它允许恶意web用户将代码植入到提供给其它用户使用的页面中.比如这些代码包括HTML代码和客户端脚本.攻击者利用XSS漏洞 ...

  3. C#中excel读取和写入

    1.方法一:采用OleDB读取EXCEL文件: 把EXCEL文件当做一个数据源来进行数据的读取操作,实例如下: public DataSet ExcelToDS(string Path) { stri ...

  4. 异常的概念和Java异常体系结构

    一. 异常的概念和Java异常体系结构     异常是程序运行过程中出现的错误.本文主要讲授的是Java语言的异常处理.Java语言的异常处理框架,     是Java语言健壮性的一个重要体现. Ja ...

  5. c版http服务器 shttpd-1.38 vs2013

    有个项目,本来是外网的.要做一个局域网版本. 项目启动就获取一大堆http的数据.考虑到可以提供http服务的软件虽然多,但是多要安装这样那样的软件,还要配置环境或者配置资源等问题. 发布的时候给人一 ...

  6. codeforces——contest 864 problemE

    Polycarp is in really serious trouble — his house is on fire! It's time to save the most valuable it ...

  7. 【BZOJ】2196: [Usaco2011 Mar]Brownie Slicing

    [题意]给定n*m的数字矩阵,要求横着切A-1刀,对每块再分别竖着切B-1刀,是最小子矩阵最大. [算法]二分+贪心 [题解]还记得提高组2015跳石头吗?这道题做法一致,只不过拓展到二维而已. 二分 ...

  8. python学习笔记(七)之列表

    列表:是一个加强版的数组,什么东西都可以往里面放. 创建列表 创建一个普通列表: >>> member = ['operating system', 'data structure' ...

  9. Vuejs - 花式渲染目标元素

    Vue.js是什么 摘自官方文档: Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架.与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用.Vue 的核心库 ...

  10. linux平台学x86汇编语言学习集合帖

    linux平台学x86汇编语言学习集合帖 linux平台学x86汇编(一):https://blog.csdn.net/shallnet/article/details/45543237 linux平 ...