摘要:本文主要向大家介绍了C#编程之c# 拉取网页,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
本文主要向大家介绍了C#编程之c# 拉取网页,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
namespace xsharp
{
class Program
{
static int writeContent(string sHtml)
{
int iBgnIdx = sHtml.IndexOf("<div id=\"chaptercontent");
if (iBgnIdx <= 0)
return -1;
int iEndIdx = sHtml.IndexOf("", iBgnIdx+1);
if (iEndIdx <= 0)
return -1;
string sDivSub = sHtml.Substring(iBgnIdx, iEndIdx - iBgnIdx);
iBgnIdx = sDivSub.IndexOf("
");
if (iBgnIdx <= 0)
return -1;
iEndIdx = sDivSub.IndexOf("<p style", iBgnIdx + 5);
if (iEndIdx <= 0)
return -1;
string sContentSub = sDivSub.Substring(iBgnIdx+5, iEndIdx - iBgnIdx-5);
sContentSub = sContentSub.Replace(" ", " ");
sContentSub = sContentSub.Replace("
", Environment.NewLine);
Console.WriteLine(sContentSub);
using (StreamWriter sw = new StreamWriter("G:\\content.html"))//将获取的内容写入文本
{
sw.Write(sContentSub);
}
return 0;
}
static void Main(string[] args)
{
try
{
WebClient MyWebClient = new WebClient();
MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于对向Internet资源的请求进行身份验证的网络凭据。
Byte[] pageData = MyWebClient.DownloadData("//wap.xxbiquge.com/59_59865/3184122.html"); //从指定网站下载数据
//string pageHtml = Encoding.Default.GetString(pageData); //如果获取网站页面采用的是GB2312,则使用这句
string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8,则使用这句
//Console.WriteLine(pageHtml);//在控制台输入获取的内容
writeContent(pageHtml);
//using (StreamWriter sw = new StreamWriter("G:\\ouput.html"))//将获取的内容写入文本
//{
// sw.Write(pageHtml);
//}
Console.ReadLine(); //让控制台暂停,否则一闪而过了
}
catch (WebException webEx)
{
Console.WriteLine(webEx.Message.ToString());
}
}
}
}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号