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

使用Scrapy爬取動態(tài)數(shù)據(jù)

 更新時間:2018年10月21日 10:31:50   作者:回憶不說話  
今天小編就為大家分享一篇關于使用Scrapy爬取動態(tài)數(shù)據(jù)的文章,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧

對于動態(tài)數(shù)據(jù)的爬取,可以選擇seleniumPhantomJS兩種方式,本文選擇的是PhantomJS。

網(wǎng)址:

1.首先第一步,對中間件的設置。

進入pipelines.py文件中:

from selenium import webdriver
from scrapy.http.response.html import HtmlResponse
from scrapy.http.response import Response
class SeleniumSpiderMiddleware(object):
  def __init__(self):
    self.driver = webdriver.PhantomJS()
  def process_request(self ,request ,spider):
    # 當引擎從調度器中取出request進行請求發(fā)送下載器之前
    # 會先執(zhí)行當前的爬蟲中間件 ,在中間件里面使用selenium
    # 請求這個request ,拿到動態(tài)網(wǎng)站的數(shù)據(jù) 然后將請求
    # 返回給spider爬蟲對象
    if spider.name == 'taobao':
      # 使用爬蟲文件的url地址
      spider.driver.get(request.url)
      for x in range(1 ,12 ,2):
        i = float(x) / 11
        # scrollTop 從上往下的滑動距離
        js = 'document.body.scrollTop=document.body.scrollHeight * %f' % i
        spider.driver.execute_script(js)
      response = HtmlResponse(url=request.url,
                  body=spider.driver.page_source,
                  encoding='utf-8',
                  request=request)
      # 這個地方只能返回response對象,當返回了response對象,那么可以直接跳過下載中間件,將response的值傳遞給引擎,引擎又傳遞給 spider進行解析
      return response

在設置中,要將middlewares設置打開。

進入settings.py文件中,將

DOWNLOADER_MIDDLEWARES = {
  'taobaoSpider.middlewares.SeleniumSpiderMiddleware': 543,
}

打開。

2.第二步,爬取數(shù)據(jù)

回到spider爬蟲文件中。

引入:

from selenium import webdriver

自定義屬性:

def __init__(self):
  self.driver = webdriver.PhantomJS()

查找數(shù)據(jù)和分析數(shù)據(jù):

def parse(self, response):
  div_info = response.xpath('//div[@class="info-cont"]')
  print(div_info)
  for div in div_info:
    title = div.xpath('.//div[@class="title-row "]/a/text()').extract_first('')
    # title = self.driver.find_element_by_class_name("title-row").text
    print('名稱:', title)
    price = div.xpath('.//div[@class="sale-row row"]/div/span[2]/strong/text()').extract_first('')

3.第三步,傳送數(shù)據(jù)到item中:

item.py文件中:

name = scrapy.Field()
price = scrapy.Field()

回到spider.py爬蟲文件中:

引入:

from ..items import TaobaospiderItem

傳送數(shù)據(jù):

#創(chuàng)建實例化對象。

item = TaobaospiderItem()
item['name'] = title
item['price'] = price
yield item

在設置中,打開:

ITEM_PIPELINES = {
  'taobaoSpider.pipelines.TaobaospiderPipeline': 300,
}

4.第四步,寫入數(shù)據(jù)庫:

進入管道文件中。

引入

import sqlite3
寫入數(shù)據(jù)庫的代碼如下:
class TaobaospiderPipeline(object):
  def __init__(self):
    self.connect = sqlite3.connect('taobaoDB')
    self.cursor = self.connect.cursor()
    self.cursor.execute('create table if not exists taobaoTable (name text,price text)')
  def process_item(self, item, spider):
    self.cursor.execute('insert into taobaoTable (name,price)VALUES ("{}","{}")'.format(item['name'],item['price']))
    self.connect.commit()
    return item
  def close_spider(self):
    self.cursor.close()
    self.connect.close()


在設置中打開:

ITEM_PIPELINES = {
  'taobaoSpider.pipelines.TaobaospiderPipeline': 300,
}

因為在上一步,我們已經(jīng)將管道傳送設置打開,所以這一步可以不用重復操作。

然后運行程序,打開數(shù)據(jù)庫查看數(shù)據(jù)。

至此,程序結束。

下附spider爬蟲文件所有代碼:

# -*- coding: utf-8 -*-
import scrapy
from selenium import webdriver
from ..items import TaobaospiderItem
class TaobaoSpider(scrapy.Spider):
  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):
    self.driver = webdriver.PhantomJS()
  def parse(self, response):
    div_info = response.xpath('//div[@class="info-cont"]')
    print(div_info)
    for div in div_info:
      title = div.xpath('.//div[@class="title-row "]/a/text()').extract_first('')
      print('名稱:', title)
      price = div.xpath('.//div[@class="sale-row row"]/div/span[2]/strong/text()').extract_first('')
      item = TaobaospiderItem()
      item['name'] = title
      item['price'] = price
      yield item
  def close(self,reason):
    print('結束了',reason)
    self.driver.quit()

關于scrapy的中文文檔:http://scrapy-chs.readthedocs.io/zh_CN/latest/faq.html

總結

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內(nèi)容請查看下面相關鏈接

相關文章

  • 詳解Python設計模式編程中觀察者模式與策略模式的運用

    詳解Python設計模式編程中觀察者模式與策略模式的運用

    這篇文章主要介紹了Python設計模式編程中觀察者模式與策略模式的運用,觀察者模式和策略模式都可以歸類為結構型的設計模式,需要的朋友可以參考下
    2016-03-03
  • Python functools模塊學習總結

    Python functools模塊學習總結

    這篇文章主要介紹了Python functools模塊學習總結,本文講解了functools.partial、functool.update_wrapper、functool.wraps、functools.reduce、functools.cmp_to_key、functools.total_ordering等方法的使用實例,需要的朋友可以參考下
    2015-05-05
  • Python使用OpenCV實現(xiàn)虛擬縮放效果

    Python使用OpenCV實現(xiàn)虛擬縮放效果

    OpenCV?徹底改變了整個圖像處理領域。從圖像分類到對象檢測,我們不僅可以使用?OpenCV?庫做一些很酷的事情,而且還可以構建一流的應用程序。本文將用OpenCV實現(xiàn)虛擬縮放,需要的可以參考一下
    2022-02-02
  • python2.7 安裝pip的方法步驟(管用)

    python2.7 安裝pip的方法步驟(管用)

    這篇文章主要介紹了python2.7 安裝pip的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-05-05
  • 用Python刪除本地目錄下某一時間點之前創(chuàng)建的所有文件的實例

    用Python刪除本地目錄下某一時間點之前創(chuàng)建的所有文件的實例

    下面小編就為大家分享一篇用Python刪除本地目錄下某一時間點之前創(chuàng)建的所有文件的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2017-12-12
  • python使用正則表達式匹配反斜杠\遇到的問題

    python使用正則表達式匹配反斜杠\遇到的問題

    在學習Python正則式的過程中,有一個問題一直困擾我,如何去匹配一個反斜杠(即“\”),下面這篇文章主要給大家介紹了關于python使用正則表達式匹配反斜杠\的相關資料,需要的朋友可以參考下
    2022-09-09
  • Django實現(xiàn)微信小程序的登錄驗證功能并維護登錄態(tài)

    Django實現(xiàn)微信小程序的登錄驗證功能并維護登錄態(tài)

    這篇文章主要介紹了Django實現(xiàn)小程序的登錄驗證功能并維護登錄態(tài),本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-07-07
  • Django Rest Framework構建API的實現(xiàn)示例

    Django Rest Framework構建API的實現(xiàn)示例

    本文主要介紹了Django Rest Framework構建API的實現(xiàn)示例,包含環(huán)境設置、數(shù)據(jù)序列化、視圖與路由配置、安全性和權限設置、以及測試和文檔生成這幾個步驟,具有一定的參考價值,感興趣的可以了解一下
    2024-08-08
  • From CSV to SQLite3 by python 導入csv到sqlite實例

    From CSV to SQLite3 by python 導入csv到sqlite實例

    今天小編就為大家分享一篇From CSV to SQLite3 by python 導入csv到sqlite實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • python數(shù)據(jù)分析之聚類分析(cluster analysis)

    python數(shù)據(jù)分析之聚類分析(cluster analysis)

    聚類分析本身不是一個特定的算法,而是要解決的一般任務。它可以通過各種算法來實現(xiàn),這些算法在理解群集的構成以及如何有效地找到它們方面存在顯著差異。這篇文章主要介紹了python數(shù)據(jù)分析之聚類分析(cluster analysis),需要的朋友可以參考下
    2021-11-11

最新評論