我的第一个Scrapy 程序 - 爬取当当网信息
admin
2023-05-04 11:41:46
0

前面已经安装了Scrapy,下面来实现第一个测试程序。

概述

Scrapy是一个爬虫框架,他的基本流程如下所示(下面截图来自互联网)

我的第一个Scrapy 程序 - 爬取当当网信息

简单的说,我们需要写一个item文件,定义返回的数据结构;写一个spider文件,具体爬取的数据程序,以及一个管道 pipeline 文件,作为后续操作,比如保存数据等等。

下面以当当网为例,看看怎么实现。
这个例子里面我想爬取的内容是前面20页的羽绒服产品,包括产品名字,链接和评论数。

过程

1. 创建一个Scrapy的项目

scrapy startproject dangdang

2. 创建一个爬虫文件**

scrapy genspider -t basic dd dangdang.com

这样他会自动创建一个爬虫文件,结构如下所示:
我的第一个Scrapy 程序 - 爬取当当网信息

3. 编写items.py

items.py

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class DangdangItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()

    title=scrapy.Field()
    url=scrapy.Field()
    comment=scrapy.Field()

4. 编写爬虫文件dd.py

前面第二步已经自动生成了一个模板,我们直接修改就行。
dd.py

# -*- coding: utf-8 -*-

import scrapy
from dangdang.items import DangdangItem
from scrapy.http import Request

class DdSpider(scrapy.Spider):
    name = 'dd'
    allowed_domains = ['dangdang.com']
    start_urls = ['http://category.dangdang.com/pg1-cid4010275.html']

    def parse(self, response):

        item=DangdangItem()
        item['title']=response.xpath(u"//a[@dd_name='单品标题']/text()").extract()
        item['url']=response.xpath("//a[@dd_name='单品标题']/@href").extract()
        item['comment']=response.xpath("//a[@dd_name='单品评论']/text()").extract()
        text = response.body
        # content_type = chardet.detect(text)
        # if content_type['encoding'] != 'UTF-8':
        #     text = text.decode(content_type['encoding'])
        # text = text.encode('utf-8')
        # print(text)

        yield item

        for i in range(2,20):
            url='http://category.dangdang.com/pg%d-cid4010275.html'%i
            yield Request(url,callback=self.parse)

5. 编写pipelines.py

为了使用pipeline,配置文件需要做个小修改,我顺便关掉了对robot文件的确认
settings.py

ROBOTSTXT_OBEY = False

ITEM_PIPELINES = {
   'dangdang.pipelines.DangdangPipeline': 300,
}

pipeline.py

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql

class DangdangPipeline(object):
    def process_item(self, item, spider):
        conn=pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='dangdang',use_unicode=True,charset='utf8')
        for i in range(0,len(item['title'])):
            title=item['title'][i]
            link=item['url'][i]
            comment=item['comment'][i]

            print(type(title))
            print(title)
            # sql="insert into dd(title,link,comment) values ('"+title+"','"+link+"','"+comment+"')"
            sql = "insert into dd(title,link,comment) values('" + title + "','" + link + "','" + comment + "')"
            try:
                conn.query(sql)
            except Exception as err:
                pass
        conn.close()

        return item

6. 创建数据库和表

我最后的数据要保存到mysql里面,python里面可以通过pymysql进行操作。我提前在mysql命令行界面里面创建了一个数据库和空表

mysql> create database dangdang;
mysql> create table dd(id int auto_increment primary, title varchar(100), link varchar(100), comment varchar(32));

7. 执行

scrapy crawl dd
如果不想看日志 可以使用
scrapy crawl dd --nolog

8. 检测结果

test.py

#!/usr/bin/env python
#! -*- coding:utf-8 -*-
# Author: Yuan Li
import pymysql
conn=pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='dangdang',use_unicode=True,charset='utf8')

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#SQL查询
cursor.execute("select * from dd")
row=cursor.fetchall()
for i in row:
    print(i)
conn.close()

结果测试成功

我的第一个Scrapy 程序 - 爬取当当网信息

相关内容

热门资讯

什么信号?多地要求干部带头缴纳... 多地要求干部带头缴纳物业费。最近一段时间,物业费成了社会关注的焦点。原因竟然是多地密集出台文件,号召...
“这不是威胁而是绝佳机遇”,默... 【文/观察者网 张菁娟】“当下挑战之所以如此巨大,是因为我们长期以来为自己制造了太多问题,而这些问题...
老杜盟友半路杀出,“闪电夺权”... 最近两天,马尼拉的政治温度直接爆表。5月11日上午,菲律宾众议院以255票赞成、26票反对、9票弃权...
“六张网”项目密集启动 进一步... 新华社北京5月13日电 题:“六张网”项目密集启动 进一步释放内需潜力经济参考报记者汪子旭近期,一批...
豪华邮轮病毒,横跨三大洲始末 5月11日,泛海探险公司确认,隶属于该公司的“洪迪厄斯”号邮轮抵达西班牙特内里费岛后,全部87名乘客...
苏泊尔球釜电饭煲不通电是什么原... 1、有可能是温度保险管出现了问题,每个电饭煲都有温度保险管,而不是家常用的保险丝,如果保险管出现了问...
九阳铁釜电饭煲不通电原因 1、可能是面板烧了。2、控制电路没有工作,先检查控制电源是否正常。电饭煲的面板显示器线路接触不良,找...
空调线控器出现“黑... 珠海总部对于退回的多联机线控器黑屏“故障”,部分是由于不清楚线控器的灯光功能,误触发线控器关闭了灯光...
长虹柜机温度传感器是多少K 每一个空调传感器的传感温度都会对应着不同的空调工作型号和参数,常见的有5K,10K和15K,当然在不...
测电笔测不出的漏电 1、如果漏电的电压比较低的话有时候测电笔就测试不出来的。2、有时候测电笔在出厂的时候没有检测好,就有...