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

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

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


代碼如下
middlewares.py代碼:
注意:自定義下載中間件,采用selenium的方式??!
# -*- 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)建在中間件的初始化方法中,適合項(xiàng)目中只有一個(gè)爬蟲。
# 爬蟲項(xiàng)目中有多個(gè)爬蟲文件的話,將driver對(duì)象的創(chuàng)建放在每一個(gè)爬蟲文件中。
# def __init__(self):
# # 在scrapy中創(chuàng)建driver對(duì)象,盡可能少的創(chuàng)建該對(duì)象。
# # 1. 在初始化方法中創(chuàng)建driver對(duì)象;
# # 2. 在open_spider中創(chuàng)建deriver對(duì)象;
# # 3. 不要將driver對(duì)象的創(chuàng)建放在process_request();
# option = FirefoxOptions()
# option.headless = True
# self.driver = webdriver.Firefox(options=option)
# 參數(shù)spider就是TaobaoSpider()類的對(duì)象
def process_request(self, request, spider):
if spider.name == "taobao":
spider.driver.get(request.url)
# 由于淘寶的頁(yè)面數(shù)據(jù)加載需要進(jìn)行滾動(dòng),但并不是所有js動(dòng)態(tài)數(shù)據(jù)都需要滾動(dòng)。
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)造成為一個(gè)Response對(duì)象,并返回。
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)站。如需爬取動(dòng)態(tài)網(wǎng)站,需要結(jié)合著selenium進(jìn)行js的渲染,才能獲取到動(dòng)態(tài)加載的數(shù)據(jù)。
如何通過(guò)selenium請(qǐng)求url,而不再通過(guò)下載器Downloader去請(qǐng)求這個(gè)url?
方法:在request對(duì)象通過(guò)中間件的時(shí)候,在中間件內(nèi)部開始使用selenium去請(qǐng)求url,并且會(huì)得到url對(duì)應(yīng)的源碼,然后再將源代碼通過(guò)response對(duì)象返回,直接交給process_response()進(jìn)行處理,再交給引擎。過(guò)程中相當(dāng)于后續(xù)中間件的process_request()以及Downloader都跳過(guò)了。
"""
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):
# 在初始化淘寶對(duì)象時(shí),創(chuàng)建driver
super(TaobaoSpider, self).__init__(name='taobao')
option = FirefoxOptions()
option.headless = True
self.driver = webdriver.Firefox(options=option)
def parse(self, response):
"""
提取列表頁(yè)的商品標(biāo)題和價(jià)格
: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、只存在一個(gè)爬蟲文件的話,driver初始化函數(shù)可以定義在middlewares.py的自定義中間件中(如上述代碼注釋初始化部分)也可以在爬蟲文件中自定義(如上述代碼在爬蟲文件中初始化)。
注意:如果只有一個(gè)爬蟲文件就不需要在自定義的process_requsests中判斷是哪一個(gè)爬蟲項(xiàng)目然后分別請(qǐng)求!
2、如果存在兩個(gè)或兩個(gè)以上爬蟲項(xiàng)目(如下圖項(xiàng)目結(jié)構(gòu))的時(shí)候,需要將driver的初始化函數(shù)定義在各自的爬蟲項(xiàng)目文件下(如上述代碼),同時(shí)需要在process_requsests判斷是那個(gè)爬蟲項(xiàng)目的請(qǐng)求!!

到此這篇關(guān)于scrapy與selenium結(jié)合爬取數(shù)據(jù)的示例代碼的文章就介紹到這了,更多相關(guān)scrapy selenium爬取數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于python實(shí)現(xiàn)的抓取騰訊視頻所有電影的爬蟲
這篇文章主要介紹了用python實(shí)現(xiàn)的抓取騰訊視頻所有電影的爬蟲,這個(gè)程序使用芒果存, 所以大家需要下載使用mongodb才可以2016-04-04
Python標(biāo)準(zhǔn)庫(kù)之time庫(kù)的使用教程詳解
這篇文章主要介紹了Python的time庫(kù)的使用教程,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)python基礎(chǔ)的小伙伴們有非常好的幫助,需要的朋友可以參考下2022-04-04
Python實(shí)現(xiàn)視頻轉(zhuǎn)換為字符畫詳解
這篇文章主要介紹了如何通過(guò)Python實(shí)現(xiàn)讀取視頻并將其轉(zhuǎn)換為字符畫的示例代碼,文中講解詳細(xì),對(duì)我們的學(xué)習(xí)和工作有一點(diǎn)的價(jià)值,感興趣的小伙伴可以了解一下2021-12-12
使用 Python 寫一個(gè)簡(jiǎn)易的抽獎(jiǎng)程序
這篇文章主要介紹了使用 Python 寫一個(gè)簡(jiǎn)易的抽獎(jiǎng)程序,本文通過(guò)實(shí)例代碼,思路講解的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12
python使用線程封裝的一個(gè)簡(jiǎn)單定時(shí)器類實(shí)例
這篇文章主要介紹了python使用線程封裝的一個(gè)簡(jiǎn)單定時(shí)器類,實(shí)例分析了Python線程的使用及定時(shí)器類的實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-05-05
python接入GoogleAuth的實(shí)現(xiàn)
經(jīng)常會(huì)用到GoogleAuth作為二次驗(yàn)證碼,本文主要介紹了python接入GoogleAuth的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08

