如何使用Scrapy结合Selenium完整爬取豆瓣阅读内容?
- 内容介绍
- 相关推荐
本文共计939个文字,预计阅读时间需要4分钟。
首先创建Scrapy项目:命令:`scrapy startproject douban_read`
创建Spider:命令:`scrapy genspider douban_spider url`
网址:`https://read.douban.com/charts`
关键注释:代码中应有注释,如有不足,请多指教。
Scrapy项目目录结构:douban_read/ ├── douban_read/ │ ├── __init__.py │ ├── items.py │ ├── middlewares.py │ ├── pipelines.py │ ├── settings.py │ └── spiders/ │ ├── __init__.py │ └── douban_spider.py ├── scrapy.cfg
首先创建scrapy项目
命令:scrapy startproject douban_read
创建spider
命令:scrapy genspider douban_spider url
网址:read.douban.com/charts
关键注释代码中有,若有不足,请多指教
scrapy项目目录结构如下
douban_spider.py文件代码
爬虫文件
import scrapy import re, json from ..items import DoubanReadItem class DoubanSpiderSpider(scrapy.Spider): name = 'douban_spider' # allowed_domains = ['www'] start_urls = ['read.douban.com/charts'] def parse(self, response): # print(response.text) # 获取图书分类的url type_urls = response.xpath('//div[@class="rankings-nav"]/a[position()>1]/@href').extract() # print(type_urls) for type_url in type_urls: # /charts?type=unfinished_column&index=featured&dcs=charts&dcm=charts-nav part_param = re.search(r'charts\?(.*?)&dcs', type_url).group(1) # read.douban.com/j/index//charts?type=intermediate_finalized&index=science_fiction&verbose=1 ajax_url = 'read.douban.com/j/index//charts?{}&verbose=1'.format(part_param) yield scrapy.Request(ajax_url, callback=self.parse_ajax, encoding='utf-8', meta={'request_type': 'ajax'}) def parse_ajax(self, response): # print(response.text) # 获取分类中图书的json数据 json_data = json.loads(response.text) for data in json_data['list']: item = DoubanReadItem() item['book_id'] = data['works']['id'] item['book_url'] = data['works']['url'] item['book_title'] = data['works']['title'] item['book_author'] = data['works']['author'] item['book_cover_image'] = data['works']['cover'] item['book_abstract'] = data['works']['abstract'] item['book_wordCount'] = data['works']['wordCount'] item['book_kinds'] = data['works']['kinds'] # 把item yield给Itempipeline yield item
item.py文件代码
项目的目标文件
# Define here the models for your scraped items # # See documentation in: # docs.scrapy.org/en/latest/topics/items.html import scrapy class DoubanReadItem(scrapy.Item): # define the fields for your item here like: book_id = scrapy.Field() book_url = scrapy.Field() book_title = scrapy.Field() book_author = scrapy.Field() book_cover_image = scrapy.Field() book_abstract = scrapy.Field() book_wordCount = scrapy.Field() book_kinds = scrapy.Field()
my_download_middle.py文件代码
所有request都会经过下载中间件,可以通过定制中间件,来完成设置代理,动态设置请求头,自定义下载等操作
import random import time from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from scrapy.docs.scrapy.org/en/latest/topics/settings.html # docs.scrapy.org/en/latest/topics/downloader-middleware.html # docs.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'douban_read' SPIDER_MODULES = ['douban_read.spiders'] NEWSPIDER_MODULE = 'douban_read.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'douban_read (+www.yourdomain.com)' # Obey robots.txt rules # robot协议 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 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', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36', } # Enable or disable spider middlewares # See docs.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'douban_read.middlewares.DoubanReadSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See docs.scrapy.org/en/latest/topics/downloader-middleware.html # 配置下载器中间件 DOWNLOADER_MIDDLEWARES = { 'douban_read.my_download_middle.MymiddleWares': 543, } # Enable or disable extensions # See docs.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See docs.scrapy.org/en/latest/topics/item-pipeline.html # 配置ITEM_PIPELINES ITEM_PIPELINES = { 'douban_read.pipelines.MongoPipeline': 300, } # Enable and configure the AutoThrottle extension (disabled by default) # See 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 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' # 配置mongo MONGO_URI = 'localhost' # 创建数据库:douban_read MONGO_DATABASE = 'douban_read'
最后启动该项目即可
scrapy crawl douban_spider
数据就保存到mongo数据库了
总结
到此这篇关于scrapy利用selenium爬取豆瓣阅读的文章就介绍到这了,更多相关scrapy用selenium爬取豆瓣阅读内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!
本文共计939个文字,预计阅读时间需要4分钟。
首先创建Scrapy项目:命令:`scrapy startproject douban_read`
创建Spider:命令:`scrapy genspider douban_spider url`
网址:`https://read.douban.com/charts`
关键注释:代码中应有注释,如有不足,请多指教。
Scrapy项目目录结构:douban_read/ ├── douban_read/ │ ├── __init__.py │ ├── items.py │ ├── middlewares.py │ ├── pipelines.py │ ├── settings.py │ └── spiders/ │ ├── __init__.py │ └── douban_spider.py ├── scrapy.cfg
首先创建scrapy项目
命令:scrapy startproject douban_read
创建spider
命令:scrapy genspider douban_spider url
网址:read.douban.com/charts
关键注释代码中有,若有不足,请多指教
scrapy项目目录结构如下
douban_spider.py文件代码
爬虫文件
import scrapy import re, json from ..items import DoubanReadItem class DoubanSpiderSpider(scrapy.Spider): name = 'douban_spider' # allowed_domains = ['www'] start_urls = ['read.douban.com/charts'] def parse(self, response): # print(response.text) # 获取图书分类的url type_urls = response.xpath('//div[@class="rankings-nav"]/a[position()>1]/@href').extract() # print(type_urls) for type_url in type_urls: # /charts?type=unfinished_column&index=featured&dcs=charts&dcm=charts-nav part_param = re.search(r'charts\?(.*?)&dcs', type_url).group(1) # read.douban.com/j/index//charts?type=intermediate_finalized&index=science_fiction&verbose=1 ajax_url = 'read.douban.com/j/index//charts?{}&verbose=1'.format(part_param) yield scrapy.Request(ajax_url, callback=self.parse_ajax, encoding='utf-8', meta={'request_type': 'ajax'}) def parse_ajax(self, response): # print(response.text) # 获取分类中图书的json数据 json_data = json.loads(response.text) for data in json_data['list']: item = DoubanReadItem() item['book_id'] = data['works']['id'] item['book_url'] = data['works']['url'] item['book_title'] = data['works']['title'] item['book_author'] = data['works']['author'] item['book_cover_image'] = data['works']['cover'] item['book_abstract'] = data['works']['abstract'] item['book_wordCount'] = data['works']['wordCount'] item['book_kinds'] = data['works']['kinds'] # 把item yield给Itempipeline yield item
item.py文件代码
项目的目标文件
# Define here the models for your scraped items # # See documentation in: # docs.scrapy.org/en/latest/topics/items.html import scrapy class DoubanReadItem(scrapy.Item): # define the fields for your item here like: book_id = scrapy.Field() book_url = scrapy.Field() book_title = scrapy.Field() book_author = scrapy.Field() book_cover_image = scrapy.Field() book_abstract = scrapy.Field() book_wordCount = scrapy.Field() book_kinds = scrapy.Field()
my_download_middle.py文件代码
所有request都会经过下载中间件,可以通过定制中间件,来完成设置代理,动态设置请求头,自定义下载等操作
import random import time from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from scrapy.docs.scrapy.org/en/latest/topics/settings.html # docs.scrapy.org/en/latest/topics/downloader-middleware.html # docs.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'douban_read' SPIDER_MODULES = ['douban_read.spiders'] NEWSPIDER_MODULE = 'douban_read.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'douban_read (+www.yourdomain.com)' # Obey robots.txt rules # robot协议 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 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', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36', } # Enable or disable spider middlewares # See docs.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'douban_read.middlewares.DoubanReadSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See docs.scrapy.org/en/latest/topics/downloader-middleware.html # 配置下载器中间件 DOWNLOADER_MIDDLEWARES = { 'douban_read.my_download_middle.MymiddleWares': 543, } # Enable or disable extensions # See docs.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See docs.scrapy.org/en/latest/topics/item-pipeline.html # 配置ITEM_PIPELINES ITEM_PIPELINES = { 'douban_read.pipelines.MongoPipeline': 300, } # Enable and configure the AutoThrottle extension (disabled by default) # See 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 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' # 配置mongo MONGO_URI = 'localhost' # 创建数据库:douban_read MONGO_DATABASE = 'douban_read'
最后启动该项目即可
scrapy crawl douban_spider
数据就保存到mongo数据库了
总结
到此这篇关于scrapy利用selenium爬取豆瓣阅读的文章就介绍到这了,更多相关scrapy用selenium爬取豆瓣阅读内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

