项目:爬取rtings耳机评测数据(scrapy)
文件结构
scrapy startproject one
:创建新项目,“one”是项目名称,自定义。
注意:项目文件名和爬虫文件名不能相同
table1.py
# -*- coding: utf-8 -*-
import scrapy
from one.items import OneItem # 红线报错也不用管,可以运行
class Table1Spider(scrapy.Spider):
name = 'table1'
allowed_domains = ['rtings.com']
start_urls = ['https://www.rtings.com/headphones/reviews/best/earbuds-gaming'] # 待爬取页面的url
def parse(self, response):
print("已进入parse函数")
# 获取表格中所有行元素
trs = response.xpath('//table[@class="simple_table-table"]/tbody/tr')
item = OneItem()
# row = 0
for tr in trs:
# if row >= 5:
# break
item['product'] = tr.xpath("./td[1]/div/a/span/text()").get()
item['wireless_gaming'] = tr.xpath("./td[2]/div/div/span/text()").get()
item['wired_gaming'] = tr.xpath("./td[3]/div/div/span/text()").get()
item['microphone'] = tr.xpath("./td[4]/a/div/span/text()").get()
item['bluetooth_ios_latency'] = tr.xpath("./td[5]/div/a/text()").get()
item['bluetooth_android_latency'] = tr.xpath("./td[6]/div/a/text()").get()
item['release_year'] = tr.xpath("./td[7]/div/span/text()").get()
item['mixed_usage'] = tr.xpath("./td[8]/div/div/span/text()").get()
item['neutral_sound'] = tr.xpath("./td[9]/div/div/span/text()").get()
item['commute_travel'] = tr.xpath("./td[10]/div/div/span/text()").get()
item['sports_fitness'] = tr.xpath("./td[11]/div/div/span/text()").get()
item['office'] = tr.xpath("./td[12]/div/div/span/text()").get()
item['phone_calls'] = tr.xpath("./td[13]/div/div/span/text()").get()
item['type'] = tr.xpath("./td[15]/div/a/text()").get()
# row += 1
yield item
print('parse结束')
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 OneItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
product = scrapy.Field()
wireless_gaming = scrapy.Field()
microphone = scrapy.Field()
wired_gaming = scrapy.Field()
bluetooth_ios_latency = scrapy.Field()
bluetooth_android_latency = scrapy.Field()
release_year = scrapy.Field()
mixed_usage = scrapy.Field()
neutral_sound = scrapy.Field()
commute_travel = scrapy.Field()
sports_fitness = scrapy.Field()
office = scrapy.Field()
phone_calls = scrapy.Field()
type = scrapy.Field()
middlewares.py
针对默认生成的模板,做的修改在:引入需要的包+修改下载器中间件(OneDownloaderMiddleware类)里的process_request函数
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import scrapy
class OneSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, dict or Item objects.
for i in result:
yield i
def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Response, dict
# or Item objects.
pass
def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated.
# Must return only requests (not items).
for r in start_requests:
yield r
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
class OneDownloaderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
"""
用chrome的无头浏览器渲染页面,再将渲染好的页面返回给爬虫文件
:param request:
:param spider:
:return:
"""
# chrome driver参数设置
chrome_options = Options()
# chrome_options.add_argument('--headless') # 以无头模式启动谷歌浏览器(没有UI界面,再后台运行)
chrome_options.add_argument('--no-sandbox') # 以最高权限运行谷歌浏览器
# chrome_options.add_argument('blink-settings=imagesEnabled=false') # 不加载图片,提升速度
chrome_options.binary_location = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe' # 手动指定chromedriver的位置
# 生成chrome_driver对象
chrome_driver = webdriver.Chrome(chrome_options=chrome_options)
# 抓取请求的页面
chrome_driver.get(request.url)
# 滚动页面:不滚到表格的位置,表格不会加载
chrome_driver.execute_script('window.scrollBy(0,4800)')
# todo:find能否简化?
# 等待,直到"show more"元素出现才进入下一句;等待最大时长600s,600s过后元素还不出现,就报错,程序停止
WebDriverWait(chrome_driver, 600).until(
lambda x: x.find_element_by_xpath("//span[@class='simple_table-view_more-button']").is_displayed())
# 点击“show more”
show = chrome_driver.find_element_by_xpath("//span[@class='simple_table-view_more-button']")
show.click()
# 获取渲染后的页面源码
html = chrome_driver.page_source
# 关闭chrome driver(浏览器)
chrome_driver.quit()
return scrapy.http.HtmlResponse(url=request.url, body=html.encode('utf-8'), encoding='utf-8', request=request)
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
pipelines.py
这里的结构比较乱,不具参考意义,具体可参考爬取汽车之家项目的pipelines.py
# -*- coding: utf-8 -*-
AH
# 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 codecs
import json
class OnePipeline(object):
def __init__(self):
self.file = codecs.open(filename='table1.csv', mode='w+', encoding='utf-8')
def process_item(self, item, spider):
context = item['product'] + ',' + item['wireless_gaming'] + ',' + item['wired_gaming'] + ',' + item[
'microphone'] + ',' + item['bluetooth_ios_latency'] + ',' + item['bluetooth_android_latency'] + ',' + item[
'release_year'][:4] + ',' + item['mixed_usage'] + ',' + item['neutral_sound'] + ',' + item[
'commute_travel'] + ',' + item['sports_fitness'] + ',' + item['office'] + ',' + item[
'phone_calls'] + ',' + item['type'] + ',' + '\n'
self.file.write(context) # write参数必为字符串
# res = dict(item)
# context = json.dumps(res, ensure_ascii=False)
# self.file.write(context)
# self.file.write(',\n')
return item
def open_spider(self, spider):
pass # 在初始化的函数里打开过了
def close_spider(self, spider):
self.file.close()
settings.py
修改robots协议;添加用户代理;启用中间件
# -*- coding: utf-8 -*-
# Scrapy settings for one 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 = 'one'
SPIDER_MODULES = ['one.spiders']
NEWSPIDER_MODULE = 'one.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
# USER_AGENT = 'one (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False # 不遵守robots协议
# 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',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'
}
# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
# SPIDER_MIDDLEWARES = {
# 'one.middlewares.OneSpiderMiddleware': 543,
# }
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
'one.middlewares.OneDownloaderMiddleware': 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 = {
'one.pipelines.OnePipeline': 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'