网络编程 —— Http使用httpClient实现页面爬虫

先去找类型的a标签 取出图片所在网址 取出https://desk.3gbizhi.com/deskMV/438.html

搭建Form界面

Http类

cs 复制代码
public static HttpClient Client { get; }
static Http()
{
    HttpClientHandler handler = new HttpClientHandler();//处理消息对象
    //ServerCertificateCustomValidationCallback  是否开启免验证策略,有的网站不安全,
    //浏览器阻止你访问,需要把验证忽略掉
    handler.ServerCertificateCustomValidationCallback = (message, cart, chain, error) => { return true; };
    Client = new HttpClient(handler);//请求对象


}

图片所在页面网址的正则

cs 复制代码
Regex imgHtml = new Regex(@"<a href=""(https://[a-zA-Z0-9/\.]+\.html)"" class=""[a-zA-Z0-9]* imgw"" target=""_blank"">" );
//< a href = "https://pic.3gbizhi.com/uploadmark/20231006/c54bae39ffc4a10b023fc5c7adfee803.jpg" class="arrows" target="_blank"><i class="fa fa-search-plus fa-fw"></i></a>
Regex picReg = new Regex(@"<a href=""(https://pic\.3gbizhi\.com/uploadmark/\d+/[a-zA-Z0-9]+\.(jpg|png))"" class=""arrows"" target=""_blank"">");
按钮的点击事件
cs 复制代码
string url = this.textBox1.Text;// 获取爬虫的url index_23.html
int start = int.Parse(this.textBox3.Text); //开始页数 index_1.html
int end = int.Parse(this.textBox4.Text); //结束页数 index_2.html
Regex reg = new Regex(@"index_\d+\.html$");
url = reg.Replace(url,""); //Replace =替换,把后面替换前面类型的字符串https://desk.3gbizhi.com/deskMV/
cs 复制代码
for (int i = start; i <=end; i++)
{
    string nowURL = $"{url}/index_{i}.html";
    HttpResponseMessage res = await Http.Client.GetAsync(nowURL);
    string data = await res.Content.ReadAsStringAsync();
     // 整体html字符串
    // 从data所有字符串匹配满足正则的字符串 返回结果是MatchCollection的数据集合
    MatchCollection maths = imgHtml.Matches(data);

    foreach (Match item in maths)
    { 

        //下面需要根据html 匹配类型以下格式图片
        var res1 =  await Http.Client.GetAsync(picURL);
        string data1 = await res1.Content.ReadAsStringAsync();

        
        string picURL1 = picReg.Match(data1).Groups[1].Value;
        Console.WriteLine(picURL1);
        downLoad(picURL1);
    }
} 
cs 复制代码
 public async void downLoad(string url)
 {
    var res =  await Http.Client.GetAsync(url);
     byte[] b1 = await res.Content.ReadAsByteArrayAsync();
     //C:\Users\Administrator\Desktop
     File.WriteAllBytes(@"C:\Users\Administrator\Desktop\PP\"+Path.GetFileName(url), b1);
 }
相关推荐
爱潜水的小L10 小时前
自学嵌入式day37,网络编程
开发语言·网络·php
ベadvance courageouslyミ10 小时前
网络编程基础(一)
网络·udp·ip
lusasky11 小时前
实现智能体调用海量api
网络
ZeroNews内网穿透11 小时前
EasyNode 结合 ZeroNews,实现远程管理服务器
运维·服务器·网络协议·安全·http
zfj32111 小时前
“昨晚快手被黑直播平台出现大量违规内容“技术解析
网络·网络安全·系统防护
TG:@yunlaoda360 云老大12 小时前
华为云国际站代理商的ESW主要有什么作用呢?
网络·数据库·华为云
向宇it12 小时前
【unity游戏开发——网络】使用Unity+PurrNet+Heathens+Steam,在 Unity 中通过 Steam与你的朋友建立联系
网络·游戏·unity·c#·游戏引擎·steam
鬼臾区12 小时前
Chapter 9 USB Device Framework 摘要1
网络
ikkkkkkkl12 小时前
计算机网络:传输层
网络·计算机网络·udp·tcp·传输层
G_H_S_3_13 小时前
【网络运维】容器、容器架构与docker部署
运维·网络·docker·架构