在实际采集网页时,可能会遇到 采集到内容中间时 就自动断开了,其中网页中间有 包含\0 或其它特殊字符无法进行 读取 ,造成网页无法采集,后改用BinaryReader 进行二进制流 读取。
最近一直在做这个内容 遇到了这个问题,在网页找了好地方 都没有现成的原码,我自己整理好后 原码 ,需要的拿去使用
以下为原码
public string GetWebPage1(string strUrl)
{//正确的采集方式 加上代理一起
string result = "";
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(strUrl);
httpRequest.Timeout = 60000;
//清缓存
httpRequest.CachePolicy = new System.Net.Cache.HttpRequestCachePolicy(System.Net.Cache.HttpRequestCacheLevel.NoCacheNoStore);//清缓存
//采集头部信息
httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
//httpRequest.Connection = "keep-alive";
httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0";
httpRequest.Host = "www.dapeige.com";
httpRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse respone = (HttpWebResponse)httpRequest.GetResponse();
//原有的
//StreamReader stream = new StreamReader(respone.GetResponseStream(), Encoding.UTF8);
//result = stream.ReadToEnd();
BinaryReader reader = new BinaryReader(respone.GetResponseStream(), Encoding.UTF8);
//读取有特殊内容的网页 按字节 从头读到尾
long byecount = 50000;//缓存5W个字节 因为你不知道具体网页有多少字节,以最大化字节计算
byte[] bufABC = new byte[byecount];//临时读入流到 字节
byte bufTMP;//临时字节 单个字节,可以进行debug 查看内容
long x1 = 0;//当前第几个字符内容
string GetHtmlALL = string.Empty;
string temp1 = string.Empty;//临时内容
//采用处错出理,就算出错了 程序继续进行 读取流内容
try
{
while (true)
{
bufTMP = reader.ReadByte();//读取流字节
bufABC[x1] = bufTMP;//加入流字节
x1 = x1 + 1;//读到第几个字节
}
}
catch (Exception myex)//数据库出错处理
{
}
//完成流采集后,进行数据交换
long x2 = 0;
long AAAcount = 0;//有用的字节总数个
while (x2< byecount)//得到当前 有用字节个数
{
if (bufABC[x2] >0)
{
AAAcount = AAAcount + 1;//得到当前 有用字节个数
}
x2 = x2 + 1;
}
byte[] bufAAA = new byte[AAAcount];//定义有用字节 数组个数
x2 = 0;
long x3 = 0;
while (x2 < byecount)
{
if (bufABC[x2] > 0)//当字节内容大于0时 说明这个节字是有用的
{
bufAAA[x3] = bufABC[x2];//将有用字节 加入到 数组
x3 = x3 + 1;
}
x2 = x2 + 1;
}
GetHtmlALL = System.Text.Encoding.UTF8.GetString(bufAAA); //将有用字节组数 转换成 字符串
result = GetHtmlALL;
return result;
}
以上为原码 已经测试过了,需要的朋友拿去用