scrapy爬虫框架实例二 当当图书信息

2023-11-06

spider.py

import scrapy
from DD.items import DdItem

class DdSpider(scrapy.Spider):
    name = 'dd'
    allowed_domains = ['http://search.dangdang.com/']
    start_urls = ['http://search.dangdang.com/?key=python&act=input&page_index=1']

    def start_requests(self):
        """
        爬虫请求之前
        :return:
        """
        for i in range(2,101):
            url='http://search.dangdang.com/?key=python&act=input&page_index='+str(i)
            yield scrapy.Request(url,self.parse)

    def parse(self, response):
        li_list=response.xpath('//div[@id="search_nature_rg"]/ul/li')
        for book in li_list:
            item=DdItem()

            #书名
            item["book_name"]=book.xpath('./a/@title').extract()
            if len(book.xpath('./a/@title').extract()) > 0:
                item["book_name"] = book.xpath('./a/@title').extract()
            else:
                item["book_name"]=["无简介信息"]

            #价格
            item["search_now_price"]=book.xpath('./p[3]/span[1]/text()').extract()

            #作者
            item["author"] = book.xpath('./p[5]/span[1]/a[1]/@title').extract()
            if len(book.xpath('./p[5]/span[1]/a[1]/@title').extract()) > 0:
                item["author"] = book.xpath('./p[5]/span[1]/a[1]/@title').extract()
            else:
                item["author"]=["无作者信息"]

            #出版社
            item["house"]=book.xpath('./p[5]/span[3]/a/@title').extract()
            if len(book.xpath('./p[5]/span[3]/a/@title').extract())>0:
                item["house"]=book.xpath('./p[5]/span[3]/a/@title').extract()
            else:
                item["house"]=["无出版社信息"]

            #出版日期
            item["data"]=book.xpath('./p[5]/span[2]/text()').extract()
            if len(book.xpath('./p[5]/span[2]/text()').extract())>0:
                item["data"] = book.xpath('./p[5]/span[2]/text()').extract()
            else:
                item["data"] =["无出版日期"]

            #评论数量
            item["review"]=book.xpath('./p[4]/a/text()').extract()
            # print(item)
            yield item

items.py

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

import scrapy


class DdItem(scrapy.Item):
    # define the fields for your item here like:
    #书名
    book_name = scrapy.Field()
    #价格
    search_now_price=scrapy.Field()
    #作者
    author=scrapy.Field()
    #出版社
    house=scrapy.Field()
    #出版日期
    data=scrapy.Field()
    #评论数量
    review=scrapy.Field()

pipelines.py

# 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


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymysql

class DdPipeline:
    def process_item(self, item, spider):
        #连接数据库
        conn=pymysql.connect(host="localhost",user="root",db="qu",passwd="123456",charset="utf8")
        #定义游标
        cur=conn.cursor()

        # 书名
        book_name = item["book_name"][0]
        # 价格
        search_now_price = item["search_now_price"][0]
        # 作者
        author = item["author"][0]
        # 出版社
        house = item["house"][0]
        # 出版日期
        data = item["data"][0]
        # 评论数量
        review = item["review"][0]

        sql="insert into dd(book_name,search_now_price,author,house,data,review)values ('%s','%s','%s','%s','%s','%s')"%(book_name,search_now_price,author,house,data,review)
        print(sql)
        cur.execute(sql)
        conn.commit()
        cur.close()
        conn.close()
        return item

settings.py

# Scrapy settings for DD project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'DD'

SPIDER_MODULES = ['DD.spiders']
NEWSPIDER_MODULE = 'DD.spiders'
LOG_LEVEL="ERROR"
FEED_EXPROT_ENCODING="UTF-8"

# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'DD.middlewares.DdSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'DD.middlewares.DdDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'DD.pipelines.DdPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

scrapy爬虫框架实例二 当当图书信息 的相关文章

随机推荐

  • C语言的排序函数qsort()详解

    一 qsort 函数的用法及使用说明 目录 一 qsort 函数的用法及使用说明 二 使用qsort 函数来求关于各种类型的 降序 排序 1 int类型的数组进行排序 2 char类型的数组进行排序 3 double类型的数组排序 与前两个
  • js数组去重的4种方法:

    js数组去重的4种方法
  • 常用符号大全

  • 华为OD机试 C++ 【座位调整】

    题目 由于疫情原因 学生之间的座位要保持一定距离 每个学生的左右都要至少有一个空座 给定一个代表座位情况的数组desk 其中1代表有学生坐在那个位置 0代表该位置为空 问你在保持疫情安全距离的前提下 我们还能安排多少学生 输入 一个整数数组
  • WPS授权过期问题解决方案——编程方法

    在使用WPS时 有时会遇到授权已到期的提示 这意味着您的WPS软件无法再正常使用 然而 通过编程 我们可以采取一些方法来解决这个问题 本文将介绍一种通过编程来解决WPS授权过期问题的方法 解决WPS授权过期问题的一种常见方法是修改系统的ho
  • python中mean的用法_Python Pandas dataframe.mean()用法及代码示例

    Python是进行数据分析的一种出色语言 主要是因为以数据为中心的python软件包具有奇妙的生态系统 Pandas是其中的一种 使导入和分析数据更加容易 Pandas dataframe mean 函数返回所请求轴的平均值 如果将方法应用
  • C语言实现二叉树(链式存储结构)+ 遍历

    C语言实现链式存储结构二叉树遍历 结构体定义及三种遍历方法 1 结构体定义 2 先序遍历 先序遍历的递归实现 先序遍历的非递归实现 3 中序遍历 中序遍历的递归实现 中序遍历的非递归实现 4 后续遍历 后序遍历的递归实现 5 二叉树的递归建
  • 九款实用的在线画图工具(那些可以替代Visio的应用)

    Visio是付费软件 通常会遇到下载 安装以及 授权 等各种问题 今天介绍的几款在线作图工具 帮你抛开下载 安装 授权等各种烦恼 1 LucidChart LucidChart是一个基于HTML5的在线流程图绘制和协作应用平台 用户可以方便
  • 冒号等于(:=)在Python语言中是什么意思?

    Python 3 8中提供了此语法 在Python语言中支持 运算符 以允许在表达式中进行变量赋值 此符号 是Python语言中的赋值运算符 主要称为海象运算符 简而言之 海象操作符压缩了我们的代码以使其更短 下面是一个非常简单的例子 wi
  • WSL编译linux-5.16.9 时出现 fatal error: libelf.h: No such file or directory

    make时出现两个错误 第一个是
  • Mac安装Android Studio并配置环境变量

    Mac安装Android Studio并配置环境变量 文章目录 Mac安装Android Studio并配置环境变量 安装JDK 下载并安装Android Studio 配置环境变量 安装JDK 检查 JDK 版本 在终端输入 java v
  • echarts地图自定义tooltip样式

    效果图 自定义tooltip样式 tooltip position 50 50 trigger item backgroundColor rgba 0 0 0 0 borderColor rgba 0 0 0 0 extraCssText
  • SQL学习笔记——REGEXP运算符

    REGEXP运算符 是正则表达式 regular expression 的缩写 正则表达式在搜索字符串时非常强大 下面是关于它的应用 1 查找名字中包含field的顾客 select from customers where last na
  • pytorch从0开始安装

    文章目录 一 安装anaconda 1 安装pytorch前需要先安装anaonda 首先进入官网 Anaconda The World s Most Popular Data Science Platform 进行安装相应的版本 2 接着
  • java编辑文件FileUtils

    FileUtiles 进行获取文件 把每行添加到字符串数组里 然后对每行进行替换 最后写回文件里 import org apache commons io FileUtils try str FileUtils readFileToStri
  • Python 学习资源 ( 整理日期2010-02-24 )

    Python 简明教程 入门必看 在线 浏览 http www woodpecker org cn 9081 doc abyteofpython cn chinese index html PDF http bbs chinaunix ne
  • 小酌Django4——博客文章展示

    小酌Django4 博客文章展示 文章列表页 已发布的文章列表展示页面 展示文章标题 交互模式下的数据读取 blog models py中创建数据模型后 Django会自动提供数据库抽象的API ORM 进行增删改查操作 使用命令pytho
  • TCP/IP 通信

    学习资料来源 正点原子STM32 目录 TCP IP TCP连接 TCP终止连接 MAC LAN8720 DMA LWIP内存分配 内存池 内存堆 数据包管理 pbuf介绍 数据包申请与释放 网络接口管理 ARP协议 TCP IP TCP是
  • input 去除边框/设置placeholder样式--SCSS

    input 去除边框 设置placeholder样式 SCSS el input edit v deep input webkit input placeholder font size 22px el input inner border
  • scrapy爬虫框架实例二 当当图书信息

    spider py import scrapy from DD items import DdItem class DdSpider scrapy Spider name dd allowed domains http search dan