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

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'

猜你喜欢

转载自blog.csdn.net/weixin_46457946/article/details/116137185