刚学了scrapy框架,找一个东西练练手
点击此处查看网页
先在cmd创建一个项目 ,记得先切换到对应的目录下面
scrapy startproject doubanTop
要把这些信息全部爬取下来故,先在items文件里面把要提取的信息的名字写好
import scrapy
class DoubantopItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()
orginal_title = scrapy.Field()
author = scrapy.Field()
publisher = scrapy.Field()
release_time = scrapy.Field()
price = scrapy.Field()
rating = scrapy.Field()
number_of_comments = scrapy.Field()
simple_comment = scrapy.Field()
import scrapy
from doubanTop.items import DoubantopItem # 把items.py里面的名字对应地引进来
class DoubanSpider(scrapy.Spider):
name = 'douban'
allowed_domains = ['douban.com']
start_urls = ['https://book.douban.com/top250?start=0']
def parse(self, response):
item = DoubantopItem()
find_all = response.xpath('//div[@class="article"]/div[@class="indent"]/table/tr[@class="item"]')
for section in find_all:
try:
title = section.xpath("td[2]/div[@class='pl2']/a/text()").extract_first().strip()
orginal_title = section.xpath("td[2]/div[@class='pl2']/span/text()").extract_first().strip()
author = section.xpath("td[2]/p[@class='pl']/text()").extract()[0].strip().split('/')[0]
publisher = section.xpath("td[2]/p[@class='pl']/text()").extract()[0].strip().split('/')[-3]
release_time = section.xpath("td[2]/p[@class='pl']/text()").extract()[0].strip().split('/')[-2]
price = section.xpath("td[2]/p[@class='pl']/text()").extract()[0].strip().split('/')[-1]
rating = section.xpath("td[2]/div[@class='star clearfix']/span[@class='rating_nums']/text()").extract_first()
number_of_comments = section.xpath("td[2]/div[@class='star clearfix']/span[@class='pl']/text()").extract_first().strip('\n )(')
simple_comment = section.xpath("td[2]/p[@class='quote']/span[@class='inq']/text()").extract_first()
item['title'] = title
item['orginal_title'] = orginal_title
item['author'] = author
item['publisher'] = publisher
item['release_time'] = release_time
item['price'] = price
item['rating'] = rating
item['number_of_comments'] = number_of_comments
item['simple_comment'] = simple_comment
yield item
except:
print('error')
pass
#注意此处的缩进
urls = ['https://book.douban.com/top250?start={0}'.format(i) for i in range(25,275,25)]
for url in urls:
yield scrapy.Request(url,callback=self.parse) # 递归调用自己的parse方法
piplines.py
此处用csv格式进行存储
import csv
class DoubantopPipeline(object):
def __init__(self):
path = 'D://douban_book_Top250.csv'
self.file = open(path,'a+',encoding='utf-8')
self.writer = csv.writer(self.file)
def process_item(self, item, spider):
self.writer.writerow(
(item['title'],item['orginal_title'],item['author'],
item['publisher'],item['release_time'],item['price'],
item['rating'],item['number_of_comments'],item['simple_comment']
)
)
return item
def close_spider(self,spider):
self.file.close()
然后再settings.py里面把对应的东西弄好
settings.py
# -*- coding: utf-8 -*-
# Scrapy settings for doubanTop 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 = 'doubanTop'
SPIDER_MODULES = ['doubanTop.spiders']
NEWSPIDER_MODULE = 'doubanTop.spiders'
# 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/70.0.3538.110 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://doc.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 = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'
# '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 = {
# 'doubanTop.middlewares.DoubantopSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'doubanTop.middlewares.DoubantopDownloaderMiddleware': 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 = {
'doubanTop.pipelines.DoubantopPipeline': 300,
}
# 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'
然后再次打开cmd,再此目录下
scrapy crawl douban
结果发现存储的csv结果是乱码的,点击此处查看csv乱码的解决方法
最后结果