前言: 学了scrapy想练习一下成果,于是有了下面的爬取网站的所有古诗的代码
目录结构:
创建项目:
scrapy startproject mySpider
main.py
from scrapy import cmdline
cmdline.execute("scrapy crawl dmoz".split())
items.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 GushiItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
name = scrapy.Field() # 古诗名
author = scrapy.Field() # 古诗作者
content = scrapy.Field() # 古诗内容
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
class GushiPipeline(object):
def process_item(self,item,spider):
# 数据清洗
item['name'] = "".join(item['name'])
item['author'] = "".join(item['author'])
item['content'] = "".join(item['content'])
item['content'] = item['content'].replace('\n','')
with open('poem.txt', 'a', encoding='UTF-8') as f:
f.write(item['name'] + '\n')
f.write(' ' + item['author'] + '\n')
f.write(item['content'] + '\n')
f.write('\n---------------------------------------------------------------\n')
return item
setting.py(关闭了遵守robots.txt协议,并且打开了pipelines)
# -*- coding: utf-8 -*-
# Scrapy settings for Gushi 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 = 'Gushi'
SPIDER_MODULES = ['Gushi.spiders']
NEWSPIDER_MODULE = 'Gushi.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'Gushi (+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
#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://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'Gushi.middlewares.GushiSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'Gushi.middlewares.GushiDownloaderMiddleware': 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
# 开启pipelines
ITEM_PIPELINES = {
'Gushi.pipelines.GushiPipeline': 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'
Poem_spider.py(下载内容的代码)
from scrapy.spiders import Spider
from Gushi.items import GushiItem
import scrapy
class poem(Spider):
name = 'dmoz'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'}
def start_requests(self):
url = 'https://www.gushiwen.org/'
yield scrapy.Request(url, headers=self.headers)
def parse(self, response):
item = GushiItem()
poems = response.xpath('//div[@class="left"]/div[@class="sons"]')
for poem in poems:
item['name'] = poem.xpath('.//p/a/b/text()').extract()
item['author'] = poem.xpath('.//p[@class="source"]/a[@target="_blank"]/text()').extract()
item['content'] = poem.xpath('.//div/div[@class="contson"]//text() | .//div/div[@class="contson"]/p//text()').extract()
# 对内容进行打印
# print(item['name'])
# print(item['author'])
# print(item['content'])
yield item
# 翻页操作
next_urls = response.xpath('//form[@id="FromPage"]/div/a/@href').extract()
if len(next_urls[0])>15: # 判断的获取到的href长度,用来翻页操作
yield scrapy.Request(next_urls[0], headers=self.headers)
else:
next_url = 'https://www.gushiwen.org' + next_urls[0]
yield scrapy.Request(next_url, headers=self.headers)
成果展示 :