欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

scrapy與selenium結(jié)合爬取數(shù)據(jù)(爬取動態(tài)網(wǎng)站)的示例代碼

 更新時間:2020年09月28日 10:08:29   作者:MXuDong  
這篇文章主要介紹了scrapy與selenium結(jié)合爬取數(shù)據(jù)的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

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對應的源碼,然后再將   源 代碼通過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)

*********************下面是相應是自定義的下載中間件的替換代碼**************************
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對應的源碼,然后再將源代碼通過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實現(xiàn)的抓取騰訊視頻所有電影的爬蟲

    基于python實現(xiàn)的抓取騰訊視頻所有電影的爬蟲

    這篇文章主要介紹了用python實現(xiàn)的抓取騰訊視頻所有電影的爬蟲,這個程序使用芒果存, 所以大家需要下載使用mongodb才可以
    2016-04-04
  • Python圖像運算之圖像灰度線性變換詳解

    Python圖像運算之圖像灰度線性變換詳解

    這篇文章將詳細講解圖像灰度線性變換,包括灰度上移、對比度增強、對比度減弱和灰度反色變換。文中的示例代碼講解詳細,需要的可以參考一下
    2022-03-03
  • Python標準庫之time庫的使用教程詳解

    Python標準庫之time庫的使用教程詳解

    這篇文章主要介紹了Python的time庫的使用教程,文中有非常詳細的代碼示例,對正在學習python基礎(chǔ)的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2022-04-04
  • Python實現(xiàn)視頻轉(zhuǎn)換為字符畫詳解

    Python實現(xiàn)視頻轉(zhuǎn)換為字符畫詳解

    這篇文章主要介紹了如何通過Python實現(xiàn)讀取視頻并將其轉(zhuǎn)換為字符畫的示例代碼,文中講解詳細,對我們的學習和工作有一點的價值,感興趣的小伙伴可以了解一下
    2021-12-12
  • python中requests模塊的使用方法

    python中requests模塊的使用方法

    這篇文章主要介紹了python中requests模塊的使用方法,實例分析了requests模塊的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-04-04
  • 如何使用pyinstaller打包32位的exe程序

    如何使用pyinstaller打包32位的exe程序

    這篇文章主要介紹了如何使用pyinstaller打包32位的exe程序,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-05-05
  • Python中的json內(nèi)置庫詳解

    Python中的json內(nèi)置庫詳解

    這篇文章主要介紹了Python中的json內(nèi)置庫詳解,在學習做自動化測試的過程中,python 里有一個內(nèi)置的 json 庫,必須要學習好,json 是用于存儲和交換數(shù)據(jù)的語法,是一種輕量級的數(shù)據(jù)交換式使用場景,需要的朋友可以參考下
    2023-08-08
  • 使用 Python 寫一個簡易的抽獎程序

    使用 Python 寫一個簡易的抽獎程序

    這篇文章主要介紹了使用 Python 寫一個簡易的抽獎程序,本文通過實例代碼,思路講解的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-12-12
  • python使用線程封裝的一個簡單定時器類實例

    python使用線程封裝的一個簡單定時器類實例

    這篇文章主要介紹了python使用線程封裝的一個簡單定時器類,實例分析了Python線程的使用及定時器類的實現(xiàn)技巧,需要的朋友可以參考下
    2015-05-05
  • python接入GoogleAuth的實現(xiàn)

    python接入GoogleAuth的實現(xiàn)

    經(jīng)常會用到GoogleAuth作為二次驗證碼,本文主要介紹了python接入GoogleAuth的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-08-08

最新評論