c#网页抓取京东商城首页案列

在C#语言中,我们可以使用一些工具类库来进行网页抓取,例如.NET Framework提供的System.Net命名空间中的HttpWebRequest和HttpWebResponse类,以及第三方类库HtmlAgilityPack。

下面是一个简单的C#程序,使用HttpWebRequest和HttpWebResponse类来抓取网页:

using System;
using System.IO;
using System.Net;

public class WebRequestExample
{
    public static void Main()
    {
        // 创建一个WebRequest对象
        WebRequest request = WebRequest.Create("http://www.example.com");

        // 发送请求并获取响应
        WebResponse response = request.GetResponse();

        // 读取响应内容
        Stream stream = response.GetResponseStream();
        StreamReader reader = new StreamReader(stream);
        string content = reader.ReadToEnd();
        
        // 关闭响应和流
        response.Close();
        reader.Close();
        stream.Close();

        // 输出网页内容
        Console.WriteLine(content);
    }
}

上述代码会获取http://www.example.com的网页内容并输出到控制台中。

如果需要解析网页内容,可以使用HtmlAgilityPack类库。下面是一个使用HtmlAgilityPack来抓取京东商城首页商品列表的示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using HtmlAgilityPack;

public class Program
{
    public static void Main()
    {
        // 发送HTTP请求获取京东商城首页内容
        using (var client = new HttpClient())
        {
            var response = client.GetAsync("https://www.jd.com/").Result;
            var responseContent = response.Content;

            // 使用HtmlAgilityPack解析HTML内容
            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(responseContent.ReadAsStringAsync().Result);

            // 获取商品列表中的商品名称和价格
            var productList = htmlDocument.DocumentNode.Descendants("ul")
                .Where(x => x.GetAttributeValue("class", "") == "clearfix")
                .FirstOrDefault();
            if (productList != null)
            {
                var items = productList.Descendants("li").ToList();
                foreach (var item in items)
                {
                    var name = item.Descendants("div")
                        .Where(x => x.GetAttributeValue("class", "") == "p-name")
                        .FirstOrDefault()?.InnerText;
                    var price = item.Descendants("div")
                        .Where(x => x.GetAttributeValue("class", "") == "p-price")
                        .FirstOrDefault()?.InnerText;
                    Console.WriteLine($"商品名称:{name},价格:{price}");
                }
            }
        }
    }
}

上述代码使用HttpClient类发送HTTP请求获取京东商城首页内容,然后使用HtmlAgilityPack解析HTML内容,并提取出商品列表中的商品名称和价格。最后输出到控制台中。

需要注意的是,网页抓取涉及到网站的隐私和版权等问题,需要遵循相关法律法规,不得擅自抓取或使用他人内容。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

然然学长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值