效果如图
完整代码如下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;
}
}
}
当然获取网页源码还有其他的方法,过后再分享
更多推荐
webclient无法获取html文件,C# WebClient获取网页源码的方法
发布评论