爬取JD商品信息


在这里插入图片描述

思路

我们可以通过构造URL来获取相应的商品页面,然后从页面中提取想要的信息即可,这里以Java为关键字,提取商品的名称、商品的价格和商品封面图片的地址。
使用了Jsoup库来解析页面和提取信息,并且写了一个商品类,用ArrayList来存储每次爬到的商品,最后用BufferedWriter将全部商品的信息保存到txt文件中。
在这里插入图片描述
在这里插入图片描述

代码

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.net.URL;
import java.util.ArrayList;

/**
 * 爬取京东商品数据
 * 如何爬取数据?
 * 获取请求返回的页面,从页面中筛选出我们想要的数据
 */
public class JDCommoditySpider {
    public static void main(String[] args) throws Exception {
        String keyword = "java";
        String url = "https://search.jd.com/Search?keyword=" + keyword;
        ArrayList<Commodity> arrayList = new ArrayList<>();
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        // 获取所有的li标签
        Elements elements = element.getElementsByTag("li");
        for (Element el : elements) {
            String imgURL = el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String name = el.getElementsByClass("p-name").eq(0).text();
            if (!imgURL.equals("") && !price.equals("") && !name.equals("")) {
                arrayList.add(new Commodity(name, price, imgURL));
            }
        }
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File("src/result/jdData.txt")));
        for (Commodity item : arrayList) {
            System.out.println(item.toString());
            bufferedWriter.write(item.toString()+"\n");
        }
        bufferedWriter.flush();
        bufferedWriter.close();
    }
}

/**
 * 商品类
 */
class Commodity {
    private String name;    // 商品的名称
    private String price;   // 商品的价格
    private String imgURL;  // 商品图片的地址

    public Commodity(String name, String price, String imgURL) {
        this.name = name;
        this.price = price;
        this.imgURL = imgURL;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getImgURL() {
        return imgURL;
    }

    public void setImgURL(String imgURL) {
        this.imgURL = imgURL;
    }

    @Override
    public String toString() {
        return "Commodity{" +
                "name='" + name + '\'' +
                ", price='" + price + '\'' +
                ", imgURL='" + imgURL + '\'' +
                '}';
    }
}

结果

在这里插入图片描述
在这里插入图片描述

总结

这次只爬取了一页的商品信息,对于其他页面的商品信息,构造URL即可(在URL中加入对应的页码参数),操作和思路都是一样的。
在这里插入图片描述

### 使用Scrapy框架爬取京东网站商品信息数据 #### 创建项目并配置环境 创建一个新的Scrapy项目用于爬取京东商品信息。通过命令行工具执行如下操作: ```bash scrapy startproject jd_spider cd jd_spider ``` 这会初始化一个名为`jd_spider`的新目录,其中包含了Scrapy项目的默认文件结构。 #### 定义Item类 在`items.py`中定义所需抓取的数据字段,例如商品名称、价格等基本信息。以下是简单的示例代码片段: ```python import scrapy class JdSpiderItem(scrapy.Item): product_name = scrapy.Field() # 商品名 price = scrapy.Field() # 单价 link = scrapy.Field() # 链接地址 shop_name = scrapy.Field() # 店铺名字 ``` 此部分设置决定了最终能够从网页上抽取哪些具体的内容[^1]。 #### 编写Spiders脚本 进入spiders子文件夹下新建Python模块文件如`jd_product.py`,在此处编写具体的爬虫逻辑。下面给出一段简化版的蜘蛛代码作为参考: ```python import scrapy from ..items import JdSpiderItem class JDProductSpider(scrapy.Spider): name = "jd_products" allowed_domains = ["search.jd.com"] def __init__(self, keyword=None, pages=10, *args, **kwargs): super(JDProductSpider, self).__init__(*args, **kwargs) base_url = 'https://search.jd.com/Search?keyword={}&enc=utf-8&page=' self.start_urls = [base_url.format(keyword)+str(i*2+1) for i in range(int(pages))] def parse(self, response): items = [] selector_list = response.xpath('//li[@class="gl-item"]') for sel in selector_list: item = JdSpiderItem() try: item['product_name'] = ''.join(sel.xpath('.//div[contains(@class,"p-name")]/a/em/text()').extract()).strip().replace('\n', '') item['price'] = sel.css('i::text').get() item['link'] = 'http:' + sel.xpath('.//div[@class="p-img"]/a/@href').get() item['shop_name'] = sel.xpath('.//span[@class="J_im_icon"]/a/text()').get() yield item except Exception as e: print(e) next_page = response.css('a.pn-next::attr(href)').get() if next_page is not None: yield response.follow(next_page, callback=self.parse) ``` 这段代码实现了启动命令接收两个参数——关键词和页数,并据此构建起始链接列表;解析每一页中的商品条目,提取目标属性填充至自定义item对象内;最后尝试跟进分页按钮继续访问后续页面直至结束。 #### 数据管道Pipeline设定 编辑settings.py开启pipelines功能并将收集到的结果存入MySQL数据库中。这里假设已经安装好相应的驱动库并且完成了必要的表单建模工作: ```python ITEM_PIPELINES = { 'jd_spider.pipelines.JdSpiderPipeline': 300, } ``` 接着,在pipelines.py里补充实际入库的方法实现细节: ```python import pymysql.cursors class JdSpiderPipeline(object): def open_spider(self, spider): db_config = getattr(spider.settings,'DB_CONFIG',{ 'host':'localhost', 'port':3306, 'user':'root', 'password':'your_password', 'db':'test_db' }) self.conn = pymysql.connect(**db_config) with self.conn.cursor() as cursor: sql_create_table=''' CREATE TABLE IF NOT EXISTS products( id INT AUTO_INCREMENT PRIMARY KEY , product_name VARCHAR(255), price DECIMAL(10 , 2 ), link TEXT, shop_name VARCHAR(255)) ''' cursor.execute(sql_create_table) def process_item(self, item, spider): insert_sql=""" INSERT INTO `products`(product_name,price,link,shop_name) VALUES (%s,%s,%s,%s); """ data_tuple=(item["product_name"],float(item["price"]),item["link"],item["shop_name"]) with self.conn.cursor() as cursor: cursor.execute(insert_sql,data_tuple) return item def close_spider(self, spider): self.conn.commit() self.conn.close() ``` 以上即为完整的基于Scrapy框架针对京东平台的商品详情数据采集方案概述。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值