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

编程知识 更新时间:2023-05-03 04:07:43

效果如图

完整代码如下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获取网页源码的方法

本文发布于:2023-04-30 12:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/dfc7a86d2726fb72ac72af8a96400985.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:源码   网页   文件   方法   webclient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 114562文章数
  • 28960阅读数
  • 0评论数