最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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對應(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引用計數(shù)操作示例

    Python引用計數(shù)操作示例

    這篇文章主要介紹了Python引用計數(shù)操作,結(jié)合實例形式分析了Python引用計數(shù)相關(guān)操作與運行機制,需要的朋友可以參考下
    2018-08-08
  • 手把手教你用python發(fā)送短消息(基于阿里云平臺)

    手把手教你用python發(fā)送短消息(基于阿里云平臺)

    這篇文章主要介紹了手把手教你用python發(fā)送短消息(基于阿里云平臺),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-03-03
  • python+pyqt5編寫md5生成器

    python+pyqt5編寫md5生成器

    這篇文章主要為大家詳細介紹了python+pyqt5編寫md5生成器,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-03-03
  • Python入門必讀的if語句嵌套方法

    Python入門必讀的if語句嵌套方法

    這篇文章主要介紹了Python入門必讀的if語句嵌套,基于前面章節(jié)介紹的3種形式的條件語句,即if、if?else和if?elif?else展開Python?if?語句嵌套的相關(guān)內(nèi)容,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-03-03
  • 快速進修Python指南之簡易跳表

    快速進修Python指南之簡易跳表

    這篇文章主要為大家介紹了Java開發(fā)者快速進修Python指南之簡易跳表示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-12-12
  • Python技巧之實現(xiàn)批量統(tǒng)一圖片格式和尺寸

    Python技巧之實現(xiàn)批量統(tǒng)一圖片格式和尺寸

    大家在工作的時候基本都會接觸到很多的圖片,有時為了不同的工作需求需要修改圖片的尺寸或者大小。本文為大家整理了Python批量轉(zhuǎn)換圖片格式和統(tǒng)一圖片尺寸,希望對大家有所幫助
    2023-05-05
  • Numpy判斷數(shù)組是否全0的三種方法

    Numpy判斷數(shù)組是否全0的三種方法

    本文介紹了三種判斷NumPy數(shù)組是否全為零的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-12-12
  • python?argparse模塊傳參用法實例

    python?argparse模塊傳參用法實例

    這篇文章主要為大家介紹了python?argparse模塊傳參用法實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-06-06
  • 一文教會你用Python3獲取網(wǎng)頁源代碼

    一文教會你用Python3獲取網(wǎng)頁源代碼

    學了python后,之前一些我們常用的方法,也可以換一種思路用python中的知識來解決,下面這篇文章主要給大家介紹了關(guān)于如何使用Python3獲取網(wǎng)頁源代碼的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-06-06
  • Python imutils 填充圖片周邊為黑色的實現(xiàn)

    Python imutils 填充圖片周邊為黑色的實現(xiàn)

    今天小編就為大家分享一篇Python imutils 填充圖片周邊為黑色的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01

最新評論

静海县| 郁南县| 万山特区| 江永县| 礼泉县| 中江县| 合江县| 聂拉木县| 吉木乃县| 达拉特旗| 祁门县| 中山市| 石门县| 永胜县| 嘉黎县| 大方县| 闽清县| 温宿县| 揭阳市| 翁牛特旗| 玉溪市| 建湖县| 昂仁县| 恩平市| 呼伦贝尔市| 波密县| 延吉市| 广宗县| 北碚区| 西乌珠穆沁旗| 余干县| 镇原县| 新巴尔虎左旗| 新晃| 苏州市| 华宁县| 兰坪| 丰镇市| 奉节县| 潞西市| 大港区|