scrapy爬取当当网Python图书的部分数据

1.下载scrapy框架

    pip install scrapy

2.在E盘下创建一个文件夹scrapy01,在命令行窗体中进入该文件夹

3.创建项目:scrapy startproject 项目名

    scrapy startproject first_scrapy

4.使用pycharm打开scrapy01文件夹

5.在items.py文件中创建所需的字段,用于保存数据

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

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

import scrapy


class FirstScrapyItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()  # 书名
    price = scrapy.Field()  # 价格
    author = scrapy.Field()  # 作者
    date = scrapy.Field()  # 出版日期
    publisher = scrapy.Field()  # 出版社

6.在spiders文件夹中创建爬虫程序test.py,代码如下:

    

# author:WN
# datetime:2019/11/3 15:29
from abc import ABC
import scrapy
from .. import items

class MySpider(scrapy.Spider, ABC):
    # 名字
    name = "mySpider"

    def start_requests(self):
        for num in range(1, 101):
            url = "http://search.dangdang.com/?key=Python&act=input&page_index=%d" % num
            # 使用yield:请求过后返回的数据等待被取走
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        try:
            data = response.text
            # scrapy是使用Xpath进行查找数据的
            # 创建选择查找类Selector()对象
            select = scrapy.Selector(text=data)
            book_data = select.xpath("//ul[@class='bigimg']/li")
            item = items.FirstScrapyItem()
            # 查找具体数据
            for book in book_data:
                title = book.xpath("./a/img/@alt").extract_first().strip()
                price = book.xpath("./p[@class='price']/span[@class='search_now_price']/text()").extract_first().lstrip('¥')
                author = book.xpath("./p[@class='search_book_author']/span/a/@title").extract_first()
                date = book.xpath("./p[@class='search_book_author']/span[2]/text()").extract_first().strip()
                publisher = book.xpath("./p[@class='search_book_author']/span/a[@name='P_cbs']/text()").extract_first()
                item['title'] = title if title else ''
                item['price'] = price if price else ''
                item['author'] = author if author else ''
                item['date'] = date if date else ''
                item['publisher'] = publisher if publisher else ''
                yield item
        except Exception as e:
            print(e)

7.在setings.py中添加配置,以便将test.py中的item推送到piplines.py的类中

# 设置将item配置到pipelines中的类中
# 项目名.pipelines.类名
# 300是一个默认整数,它可以是任意整数
ITEM_PIPELINES = {
    'first_scrapy.pipelines.FirstScrapyPipeline': 300,
}

8.编写pipelines.py的代码,前提先创建mysql数据库book和表books:

create database book;
use book;
set character_set_results=gbk;
create table books(
bTitle varchar(256) primary key,
bPrice varchar(50),
bAuthoe varchar(50),
bDate varchar(32),
bPublisher varchar(256)
);
# -*- coding: utf-8 -*-

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


class FirstScrapyPipeline(object):
    # spider爬虫一开始就会执行下面的函数
    def open_spider(self, spider):
        print('opened')
        try:
            # 连接数据库
            self.con = pymysql.connect(host='localhost', port=3306, user='root', password='root', db='book', charset='utf8')
            # 创建游标
            self.cursor = self.con.cursor()
            self.opened = True
            self.count = 0
        except Exception as e:
            print(e)
            self.opened = False

    # spider爬虫关闭执行函数
    def close_spider(self, spider):
        if self.opened:
            self.con.commit()
            self.con.close()
            self.opened = False
        print("close")
        print("总共爬取:", self.count, "本书籍")

    def process_item(self, item, spider):
        try:
            print(item['title'])
            print(item['price'])
            print(item['author'])
            print(item['date'])
            print(item['publisher'])
            if self.opened:
                self.cursor.execute(
                    'insert into books(bTitle,bPrice,bAuthor,bDate,bPublisher) values (%s,%s,%s,%s,%s)', (
                        item['title'], item['price'], item['author'], item['date'], item['publisher'])
                )
                self.count += 1
        except Exception as err:
            print(err)
        return item

9.运行此项目

    (1)在命令行窗体中运行:scrapy crawl 爬虫程序名 -s LOG_ENABLED=False,后边的参数是不显示调试信息

              scrapy crawl mySpider -s LOG_ENABLED=False

    (2)在spiders文件夹的上一级文件夹下创建run.py,运行此文件就可以运行该项目(不在dos窗口中运行项目)代码如下:

          

# author:WN
# datetime:2019/11/3 15:36
from scrapy import cmdline
# 运行语句,不需要再打开dos窗口
# scrapy crawl 爬虫名 不显示调试信息的参数
cmdline.execute("scrapy crawl mySpider -s LOG_ENABLED=False".split())

 

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Scrapy是一个Python爬虫框架,它提供了一种快速、高效地从网站抓取数据的方式。下面是使用Scrapy框架爬取网页的基本步骤: 1. 创建Scrapy项目 在命令行中使用以下命令创建Scrapy项目: ``` scrapy startproject <project_name> ``` 这将在当前目录下创建一个名为`<project_name>`的文件夹,其中包含Scrapy项目的基本结构。 2. 创建Spider 在Scrapy中,Spider是一个用于定义如何爬取网站内容的类。创建一个Spider需要继承`scrapy.Spider`类,并重写一些方法来定义如何爬取网站内容。 以下是一个示例Spider: ```python import scrapy class MySpider(scrapy.Spider): name = 'myspider' start_urls = ['http://www.example.com'] def parse(self, response): # 在这里定义如何解析网页内容 pass ``` 在上面的示例中,`name`属性定义了Spider的名称,`start_urls`属性指定了要爬取的初始URL。`parse()`方法定义了如何解析网页内容。 3. 解析网页内容 在`parse()`方法中,可以使用Scrapy提供的`Selector`对象来选择并解析网页内容。以下是一个示例: ```python def parse(self, response): title = response.css('title::text').get() body = response.css('body::text').get() yield { 'title': title, 'body': body } ``` 在上面的示例中,我们使用CSS选择器选择了网页的标题和正文内容,并将它们存储在一个字典中,通过`yield`关键字返回给Scrapy框架。 4. 运行Spider 使用以下命令运行Spider: ``` scrapy crawl <spider_name> ``` 其中,`<spider_name>`为你定义的Spider名称。 通过以上步骤,你就可以使用Scrapy框架爬取网页了。当然,还有很多高级功能和配置可以使用,你可以参考Scrapy的官方文档进行学习和实践。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值