scrapy與selenium結(jié)合爬取數(shù)據(jù)(爬取動態(tài)網(wǎng)站)的示例代碼
scrapy框架只能爬取靜態(tài)網(wǎng)站。如需爬取動態(tài)網(wǎng)站,需要結(jié)合著selenium進行js的渲染,才能獲取到動態(tài)加載的數(shù)據(jù)。
如何通過selenium請求url,而不再通過下載器Downloader去請求這個url?
方法:在request對象通過中間件的時候,在中間件內(nèi)部開始使用selenium去請求url,并且會得到url對應(yīng)的源碼,然后再將 源 代碼通過response對象返回,直接交給process_response()進行處理,再交給引擎。過程中相當于后續(xù)中間件的process_request()以及Downloader都跳過了。
相關(guān)的配置:
1、scrapy環(huán)境中安裝selenium:pip install selenium

2、確保python環(huán)境中有phantomJS(無頭瀏覽器)

對于selenium的主要操作是下載中間件部分如下圖:


代碼如下
middlewares.py代碼:
注意:自定義下載中間件,采用selenium的方式?。?br />
# -*- 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 import webdriver
from selenium.webdriver import FirefoxOptions
from scrapy.http import HtmlResponse, Response
import time
class TaobaospiderSpiderMiddleware(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 TaobaospiderDownloaderMiddleware(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):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None
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)
*********************下面是相應(yīng)是自定義的下載中間件的替換代碼**************************
class SeleniumTaobaoDownloaderMiddleware(object):
# 將driver創(chuàng)建在中間件的初始化方法中,適合項目中只有一個爬蟲。
# 爬蟲項目中有多個爬蟲文件的話,將driver對象的創(chuàng)建放在每一個爬蟲文件中。
# def __init__(self):
# # 在scrapy中創(chuàng)建driver對象,盡可能少的創(chuàng)建該對象。
# # 1. 在初始化方法中創(chuàng)建driver對象;
# # 2. 在open_spider中創(chuàng)建deriver對象;
# # 3. 不要將driver對象的創(chuàng)建放在process_request();
# option = FirefoxOptions()
# option.headless = True
# self.driver = webdriver.Firefox(options=option)
# 參數(shù)spider就是TaobaoSpider()類的對象
def process_request(self, request, spider):
if spider.name == "taobao":
spider.driver.get(request.url)
# 由于淘寶的頁面數(shù)據(jù)加載需要進行滾動,但并不是所有js動態(tài)數(shù)據(jù)都需要滾動。
for x in range(1, 11, 2):
height = float(x) / 10
js = "document.documentElement.scrollTop = document.documentElement.scrollHeight * %f" % height
spider.driver.execute_script(js)
time.sleep(0.2)
origin_code = spider.driver.page_source
# 將源代碼構(gòu)造成為一個Response對象,并返回。
res = HtmlResponse(url=request.url, encoding='utf8', body=origin_code, request=request)
# res = Response(url=request.url, body=bytes(origin_code), request=request)
return res
if spider.name == 'bole':
request.cookies = {}
request.headers.setDefault('User-Agent','')
return None
def process_response(self, request, response, spider):
print(response.url, response.status)
return response
taobao.py 代碼如下:
# -*- coding: utf-8 -*-
import scrapy
from selenium import webdriver
from selenium.webdriver import FirefoxOptions
class TaobaoSpider(scrapy.Spider):
"""
scrapy框架只能爬取靜態(tài)網(wǎng)站。如需爬取動態(tài)網(wǎng)站,需要結(jié)合著selenium進行js的渲染,才能獲取到動態(tài)加載的數(shù)據(jù)。
如何通過selenium請求url,而不再通過下載器Downloader去請求這個url?
方法:在request對象通過中間件的時候,在中間件內(nèi)部開始使用selenium去請求url,并且會得到url對應(yīng)的源碼,然后再將源代碼通過response對象返回,直接交給process_response()進行處理,再交給引擎。過程中相當于后續(xù)中間件的process_request()以及Downloader都跳過了。
"""
name = 'taobao'
allowed_domains = ['taobao.com']
start_urls = ['https://s.taobao.com/search?q=%E7%AC%94%E8%AE%B0%E6%9C%AC%E7%94%B5%E8%84%91&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.2017.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170306']
def __init__(self):
# 在初始化淘寶對象時,創(chuàng)建driver
super(TaobaoSpider, self).__init__(name='taobao')
option = FirefoxOptions()
option.headless = True
self.driver = webdriver.Firefox(options=option)
def parse(self, response):
"""
提取列表頁的商品標題和價格
:param response:
:return:
"""
info_divs = response.xpath('//div[@class="info-cont"]')
print(len(info_divs))
for div in info_divs:
title = div.xpath('.//a[@class="product-title"]/@title').extract_first('')
price = div.xpath('.//span[contains(@class, "g_price")]/strong/text()').extract_first('')
print(title, price)
settings.py代碼如下圖:

關(guān)于代碼中提到的初始化driver的位置有以下兩種情況:
1、只存在一個爬蟲文件的話,driver初始化函數(shù)可以定義在middlewares.py的自定義中間件中(如上述代碼注釋初始化部分)也可以在爬蟲文件中自定義(如上述代碼在爬蟲文件中初始化)。
注意:如果只有一個爬蟲文件就不需要在自定義的process_requsests中判斷是哪一個爬蟲項目然后分別請求!
2、如果存在兩個或兩個以上爬蟲項目(如下圖項目結(jié)構(gòu))的時候,需要將driver的初始化函數(shù)定義在各自的爬蟲項目文件下(如上述代碼),同時需要在process_requsests判斷是那個爬蟲項目的請求?。?br />

到此這篇關(guān)于scrapy與selenium結(jié)合爬取數(shù)據(jù)的示例代碼的文章就介紹到這了,更多相關(guān)scrapy selenium爬取數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
手把手教你用python發(fā)送短消息(基于阿里云平臺)
這篇文章主要介紹了手把手教你用python發(fā)送短消息(基于阿里云平臺),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03
Python技巧之實現(xiàn)批量統(tǒng)一圖片格式和尺寸
大家在工作的時候基本都會接觸到很多的圖片,有時為了不同的工作需求需要修改圖片的尺寸或者大小。本文為大家整理了Python批量轉(zhuǎn)換圖片格式和統(tǒng)一圖片尺寸,希望對大家有所幫助2023-05-05
Python imutils 填充圖片周邊為黑色的實現(xiàn)
今天小編就為大家分享一篇Python imutils 填充圖片周邊為黑色的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01

