webclient无法获取html文件,C# WebClient获取网页源码的方法

效果如图

584f77fc562e8.jpg

完整代码如下using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

//引入以下命名空间

using System.Net;

using System.IO;

using System.Threading;

namespace splitstr

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

Thread t = null;

Encoding EE = Encoding.UTF8;//网页编码,根据实际情况来哈

private void bt_gethtml_Click(object sender, EventArgs e)

{

if (tb_url.Text.Trim() != "")

{

t = new Thread(new ThreadStart(Ss));

t.Start();

}

}

private delegate void SetObject();

private void Ss()

{

//CheckForIllegalCrossThreadCalls = false;

this.Invoke(new SetObject(delegate { bt_gethtml.Enabled = tb_url.Enabled = false; }));

this.Invoke(new SetObject(delegate { richTextBox1.Text = GetHtml(tb_url.Text.Trim(), EE); }));

this.Invoke(new SetObject(delegate { bt_gethtml.Enabled = tb_url.Enabled = true; }));

t.Abort();

}

private string GetHtml(string url,Encoding ecd)

{

//参数说明:目标网址,网页编码

string htmldata = "获取网页内容失败";

try

{

WebClient wclient = new WebClient();//实例化WebClient类对象

wclient.BaseAddress = url;//设置WebClient的基URI

wclient.Encoding = ecd;//指定下载字符串的编码方式

//为WebClient类对象添加标头

wclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

//使用OpenRead方法获取指定网站的数据,并保存到Stream流中

Stream stream = wclient.OpenRead(url);

//使用流Stream声明一个流读取变量sreader

StreamReader sreader = new StreamReader(stream);

string str = string.Empty;//声明一个变量,用来保存一行从WebCliecnt下载的数据

//循环读取从指定网站获得的数据

while ((str = sreader.ReadLine()) != null)

{

htmldata += str + "\n";

}

}

catch { }

return htmldata;

}

}

}

当然获取网页源码还有其他的方法,过后再分享

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值