京东热卖手机信息爬取实战:Scrapy框架应用

本文将使用Python和Scrapy框架来爬取京东网站热卖手机信息,并保存为JSON文件。我们将抓取指定品牌的手机信息,包括名称、价格、评价数量、是否自营和详细参数,同时使用一些反反爬技巧来应对京东网站的反爬机制。

1. 环境准备

首先,你需要安装以下库:

pip install scrapy scrapy-fake-useragent

此外,你需要配置代理服务器,建议使用shadowsocks等工具。

2. 代码实现

import scrapy
import json

class JdSpider(scrapy.Spider):
    name = 'jd'
    allowed_domains = ['jd.com']
    start_urls = ['https://www.jd.com/']
    custom_settings = {
        'DOWNLOADER_MIDDLEWARES': {
            'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
            'scrapy_fake_useragent.middleware.RandomUserAgentMiddleware': 400,
            'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 110,
            'jd.middlewares.ProxyMiddleware': 100
        },
        'FEED_FORMAT': 'json',
        'FEED_URI': 'phones.json'
    }

    def parse(self, response):
        # 搜索页URL
        search_url = 'https://search.jd.com/Search?keyword={}&enc=utf-8'

        # 三个品牌的名称
        brands = ['iPhone', '华为', '小米']

        for brand in brands:
            # 构造搜索页面URL
            url = search_url.format(brand)

            yield scrapy.Request(url, callback=self.parse_search, meta={'brand': brand})

    def parse_search(self, response):
        # 获取品牌名称
        brand = response.meta['brand']

        # 遍历搜索结果列表
        for item in response.xpath('//li[@class="gl-item"]'):
            # 获取商品名称
            name = item.xpath('.//div[@class="p-name"]/a/em/text()')[0].extract()

            # 获取商品价格
            price = item.xpath('.//div[@class="p-price"]/strong/i/text()')
            price = float(price[0].extract()) if price else None

            # 获取评价数量
            review_count = item.xpath('.//div[@class="p-commit"]/strong/a/text()')
            review_count = int(review_count[0].extract().strip('()')) if review_count else None

            # 是否为自营商品
            is_selfsell = bool(item.xpath('.//div[@class="p-icons"]/i[contains(@class, "self-support")]/@class'))

            # 如果有名称、价格、评价数量,则进一步获取详细信息
            if name and price and review_count is not None:
                yield scrapy.Request(item.xpath('./div[@class="gl-i-wrap"]/a/@href')[0].extract(), 
                                     callback=self.parse_detail, 
                                     meta={'brand': brand, 'name': name, 'price': price, 
                                           'review_count': review_count, 'is_selfsell': is_selfsell})

        # 翻页
        next_page = response.xpath('//a[@class="pn-next"]/@href')
        if next_page:
            yield scrapy.Request(response.urljoin(next_page[0].extract()), callback=self.parse_search, meta={'brand': brand})

    def parse_detail(self, response):
        # 获取品牌名称、商品名称、价格、评价数量和是否自营
        brand = response.meta['brand']
        name = response.meta['name']
        price = response.meta['price']
        review_count = response.meta['review_count']
        is_selfsell = response.meta['is_selfsell']

        # 获取手机的详细参数信息
        params = {}
        for item in response.xpath('//div[@class="Ptable"]/div[@class="Ptable-item"]'):
            key = item.xpath('.//dt/text()').extract()[0].strip()
            value = item.xpath('.//dd/text()').extract()[0].strip()
            params[key] = value

        # 将所有信息保存到item中
        item = {
            'brand': brand,
            'name': name,
            'price': price,
            'review_count': review_count,
            'is_selfsell': is_selfsell,
            'params': params
        }

        yield item

3. 运行代码

将以上代码保存为jd.py文件,然后在命令行中进入该文件所在的目录,执行以下命令:

scrapy runspider jd.py

等待程序运行完毕,即可在当前目录下看到phones.json文件,其中包含了所有抓取到的手机信息。

4. 注意事项

  • 代码中使用了第三方库,需要先安装:pip install scrapy scrapy-fake-useragent
  • 代码中使用了代理,需要先安装shadowsocks并配置好代理服务器。
  • 代码中使用了xpath选择器来提取页面信息,如果不熟悉xpath可以参考相关文档。
  • 由于京东网站的反爬机制比较强,所以需要使用一些反反爬技巧,例如设置请求头、使用代理等。
  • 可以根据实际需要修改代码中的品牌列表、爬取深度、保存文件格式等。

通过本文的介绍,你已经学会了如何使用Scrapy框架爬取京东网站的热卖手机信息。希望本文对你有所帮助!


原文地址: https://www.cveoy.top/t/topic/ol9F 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录