C#使用WebClient登录网站并抓取登录后的网页信息实现方法
作者:roucheng 时间:2022-05-19 10:43:24
本文实例讲述了C#使用WebClient登录网站并抓取登录后的网页信息实现方法。分享给大家供大家参考,具体如下:
C#登录网站实际上就是模拟浏览器提交表单,然后记录浏览器响应返回的会话Cookie值,再次发送请求时带着这个会话cookie值去请求就可以实现模拟登录的效果了。
如下类CookieAwareWebClient实现在发送请求时都带着cookie。
public class CookieAwareWebClient : WebClient
{
private CookieContainer cookie = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = cookie;
}
return request;
}
}
如下是模拟表单提交登录的使用示例:
var client = new CookieAwareWebClient();
client.BaseAddress = @"https://hovertree.net/any/base/url/";
var loginData = new NameValueCollection();
loginData.Add("login", "YourLogin");
loginData.Add("password", "YourPassword");
client.UploadValues("login.php", "POST", loginData);
//Now you are logged in and can request pages
string htmlSource = client.DownloadString("index.php");
希望本文所述对大家C#程序设计有所帮助。
标签:C#,WebClient,登录,抓取
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解maven配置多仓库的方法示例
2021-06-10 14:13:22
![](https://img.aspxhome.com/file/2023/2/90972_0s.png)
计算机编程语言发展史
2022-10-07 21:28:49
![](https://img.aspxhome.com/file/2023/7/69947_0s.png)
解决SpringMVC项目连接RabbitMQ出错的问题
2022-12-22 13:05:51
![](https://img.aspxhome.com/file/2023/4/63034_0s.jpg)
springcloud引入spring-cloud-starter-openfeign失败的解决
2022-10-30 19:15:09
![](https://img.aspxhome.com/file/2023/7/110827_0s.png)
Android仿微信Viewpager-Fragment惰性加载(lazy-loading)
2023-12-16 23:50:59
![](https://img.aspxhome.com/file/2023/9/108269_0s.gif)
Java开发利器之Guava Cache的使用教程
2022-03-20 19:22:02
Java Arrays工具类用法详解
2023-12-19 13:08:00
![](https://img.aspxhome.com/file/2023/7/61807_0s.png)
java应用占用内存过高排查的解决方案
2023-09-21 12:47:30
![](https://img.aspxhome.com/file/2023/4/77464_0s.jpg)
java并发编程_线程池的使用方法(详解)
2023-03-29 22:23:00
![](https://img.aspxhome.com/file/2023/1/69711_0s.png)
C#编程获取IP地址的方法示例
2023-06-16 21:18:20
C#用NPOI导出导入Excel帮助类
2022-09-27 00:23:43
java编译器和JVM的区别
2023-07-18 20:34:48
Java实现拖拽列表项的排序功能
2023-11-28 23:39:00
Spring Data JPA查询方式及方法名查询规则介绍
2022-07-13 19:31:20
![](https://img.aspxhome.com/file/2023/4/81294_0s.png)
feign实现传递参数的三种方式小结
2021-06-18 00:09:53
![](https://img.aspxhome.com/file/2023/0/62740_0s.jpg)
用Linq从一个集合选取几列得到一个新的集合(可改列名)
2023-08-23 22:48:23
![](https://img.aspxhome.com/file/2023/1/68081_0s.png)
用Java连接sqlserver数据库时候几个jar包的区别分析
2021-11-07 02:18:01
Java经典面试题最全汇总208道(三)
2023-11-15 23:30:42
![](https://img.aspxhome.com/file/2023/6/59066_0s.jpg)
Android-Service实现手机壁纸自动更换
2022-05-21 23:15:35
![](https://img.aspxhome.com/file/2023/9/103899_0s.gif)
Java 程序内部是如何执行的?
2022-04-29 20:18:36
![](https://img.aspxhome.com/file/2023/0/89480_0s.png)