使用终端创建项目命令: scrapy  startproject  hongxiu

然后进入项目命令:cd  hongxiu

接着创建爬取的项目名字和网址,命令:scrapy  genspider  hongxiu  hongxiu.com

运行:scrapy ceawl hongxiu
 

hongxiu.py

# -*- coding: utf-8 -*-
import scrapy
from .. items import HongxiuItem

class XiuSpider(scrapy.Spider):
def __init__(self):
self.pageNum = 1
name = 'xiu'
allowed_domains = ['hongxiu.com']
start_urls = ["https://www.hongxiu.com/finish"]

def parse(self, response):
print("开始爬行")
div_list = response.xpath('//div[@class="right-book-list"]/ul/li')
for div in div_list:
title = div.xpath(".//div[@class='book-info']/h3/a/@title").extract_first()
href = 'http://www.hongxiu.com' + div.xpath(".//div[@class='book-info']/h3/a/@href").extract_first()
auth = div.xpath(".//div[@class='book-info']/h4/a/text()").extract_first()
type = div.xpath(".//div[@class='book-info']/p/span/text()").extract_first()
state = div.xpath(".//div[@class='book-info']/p/span[2]/text()").extract_first()
count = div.xpath(".//div[@class='book-info']/p/span[3]/text()").extract_first()
intro_li = div.xpath("normalize-space(.//div[@class='book-info']/p/text())").extract_first()
cover_img = 'http:' + div.xpath(".//div[@class='book-img']/a//img/@src").extract_first()

item = HongxiuItem()
item['title'] = title
item['auth'] = auth
item['type'] = type
item['state'] = state
item['state'] = state
item['count'] = count
item['href'] = href
item['intro_li'] = intro_li
item['cover_img'] = [cover_img]

yield item
self.pageNum += 1
next_url = "https://www.hongxiu.com/finish?pageSize=10&gender=2&catId=-1&isFinish=1&isVip=-1&size=-1&updT=-1&orderBy=0&pageNum=" + str(self.pageNum)
print(next_url)
yield scrapy.Request(url=next_url, callback=self.parse)

item.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 HongxiuItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()
auth = scrapy.Field()
type = scrapy.Field()
state = scrapy.Field()
count = scrapy.Field()
href = scrapy.Field()
intro_li = scrapy.Field()
cover_img = scrapy.Field()
pass

pipelines.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 HongxiuPipeline(object):
def __init__(self):
self.connect = pymysql.connect(host='localhost', user='root', password='123456', db='fiction', port=3306,
charset='utf8mb4')
self.cursor = self.connect.cursor()

def process_item(self, item, spider):
# self.connect.cursor()
self.cursor.execute("INSERT INTO wd(title,auth,type,state,count,href,intro_li) VALUES('{}','{}','{}','{}','{}','{}','{}')".format(item['title'], item['auth'], item['type'],
item['state'], item['count'], item['href'],
item['intro_li']))
self.connect.commit()
return item

def close_spider(self, spider):
self.cursor.close()
self.connect.close()

settings.py

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

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

BOT_NAME = 'hongxiu'

SPIDER_MODULES = ['hongxiu.spiders']
NEWSPIDER_MODULE = 'hongxiu.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'hongxiu (+http://www.yourdomain.com)'

# 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://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
# 设置item时间延迟
# 250ms of delay
# DOWNLOAD_DELAY = 0.25
# 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://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'hongxiu.middlewares.HongxiuSpiderMiddleware': 543,
#}

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

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

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'hongxiu.pipelines.HongxiuPipeline': 300,
'scrapy.pipelines.images.ImagesPipeline': 1

}
# 图片存储路径
IMAGES_STORE = "image"
IMAGES_URLS_FIELD = 'cover_img'


# mysql数据库的配置信息
MYSQL_HOST = '127.0.0.1'
# 数据库名字
MYSQL_DB = "fiction"
# 数据库账号
MYSQL_USER = 'root'
# 数据库密码
MYSQL_PASSWORD = '123456'
# 数据库端口号 ,在dbhelper中使用
MYSQL_PORT = 3306
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.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://doc.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'

运行结果:

scrapy爬取红袖添香并存入mysql_mysql