尚矽谷讀書網爬取筆記
阿新 • • 發佈:2022-04-08
#read.py
import scrapy
from readbook.items import ReadbookItem
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class ReadSpider(CrawlSpider):
name = 'read'
allowed_domains = ['www.dushu.com']
start_urls = ['https://www.dushu.com/book/1188_1.html']
rules = (
Rule(LinkExtractor(allow=r'/book/\d+/'), callback='parse_item', follow=True),
)
def parse_item(self, response):
img_list=response.xpath('//div[@class="bookslist"]//img')
for img in img_list:
src=img.xpath('./@data-original').extract_first()
name=img.xpath('./@alt').extract_first()
book=ReadbookItem(name=name,src=src)
yield book
#settings.py
DB_host='mysql主機地址'
DB_port=3306#埠號
DB_user='root'#使用者名稱
DB_password='1234'
DB_name='spider01'#資料庫名
#utf-8的-不允許寫,識別不了
DB_charset='utf-8'
BOT_NAME = 'readbook'
SPIDER_MODULES = ['readbook.spiders']
NEWSPIDER_MODULE = 'readbook.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'readbook (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# 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 = {
# 'readbook.middlewares.ReadbookSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'readbook.middlewares.ReadbookDownloaderMiddleware': 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 = {
'readbook.pipelines.ReadbookPipeline': 300,
#MysqlPipline
'readbook.pipelines.MysqlPipeline': 301,
}
# 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'
#piplines.py
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
class ReadbookPipeline:
def open_spider(self,spider):
self.fp=open('book.json','w',encoding='utf-8')
def process_item(self, item, spider):
self.fp.write(str(item))
return item
def close_spider(self,spider):
self.fp.close()
#載入settings檔案
from scrapy.utils.project import get_project_settings
import pymysql
class MysqlPipline:
def open_spider(self,spider):
settings=get_project_settings()
'''DB_host='mysql主機地址'
DB_port=3306#埠號
DB_user='root'#使用者名稱
DB_password='1234'
DB_name='spider01'#資料庫名
DB_harset='utf-8'
'''
self.host=settings['DB_host']
self.port=settings['DB_port']
self.user=settings['DB_user']
self.password=settings['DB_password']
self.name=settings['DB_name']
self.charest=settings['DB_charset']
self.coonect()
def connect(self):
self.conn=pymysql.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
db=self.name,
charset=self.charest
)
self.cursor=self.conn.cursor()#執行sql語句
def process_item(self,item,spider):
sql='insert into book(name,src) values("{}","{}")'.format(item['name'],item['src'])
self.cursor.execute(sql)#執行sql語句
self.conn.commit()#提交
return item
def close_spider(self,spider):
self.cursor.close()
self.conn.close()
#items.py
import scrapy
class ReadbookItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
name=scrapy.Field()
src=scrapy.Field()