主頁(yè) > 知識(shí)庫(kù) > Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫(kù)的方法示例

Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫(kù)的方法示例

熱門標(biāo)簽:清遠(yuǎn)360地圖標(biāo)注方法 西藏智能外呼系統(tǒng)五星服務(wù) 在哪里辦理400電話號(hào)碼 平頂山外呼系統(tǒng)免費(fèi) 原裝電話機(jī)器人 工廠智能電話機(jī)器人 400電話申請(qǐng)服務(wù)商選什么 千陽(yáng)自動(dòng)外呼系統(tǒng) 江蘇客服外呼系統(tǒng)廠家

在django項(xiàng)目根目錄位置創(chuàng)建scrapy項(xiàng)目,django_12是django項(xiàng)目,ABCkg是scrapy爬蟲項(xiàng)目,app1是django的子應(yīng)用

2.在Scrapy的settings.py中加入以下代碼

import os
import sys
sys.path.append(os.path.dirname(os.path.abspath('.')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_12.settings'  # 項(xiàng)目名.settings
import django
django.setup()

3.編寫爬蟲,下面代碼以ABCkg為例,abckg.py

# -*- coding: utf-8 -*-
import scrapy
from ABCkg.items import AbckgItem
 
class AbckgSpider(scrapy.Spider):
  name = 'abckg'  #爬蟲名稱
  allowed_domains = ['www.abckg.com'] # 允許爬取的范圍
  start_urls = ['http://www.abckg.com/'] # 第一次請(qǐng)求的地址
  def parse(self, response):
    print('返回內(nèi)容:{}'.format(response))
    """
    解析函數(shù)
    :param response: 響應(yīng)內(nèi)容
    :return:
    """
    listtile = response.xpath('//*[@id="container"]/div/div/h2/a/text()').extract()
    listurl = response.xpath('//*[@id="container"]/div/div/h2/a/@href').extract()
 
    for index in range(len(listtile)):
      item = AbckgItem()
      item['title'] = listtile[index]
      item['url'] = listurl[index]
      yield scrapy.Request(url=listurl[index],callback=self.parse_content,method='GET',dont_filter=True,meta={'item':item})
    # 獲取下一頁(yè)
    nextpage = response.xpath('//*[@id="container"]/div[1]/div[10]/a[last()]/@href').extract_first()
    print('即將請(qǐng)求:{}'.format(nextpage))
    yield scrapy.Request(url=nextpage,callback=self.parse,method='GET',dont_filter=True)
    # 獲取詳情頁(yè)
  def parse_content(self,response):
    item = response.meta['item']
    item['content'] = response.xpath('//*[@id="post-1192"]/dd/p').extract()
    print('內(nèi)容為:{}'.format(item))
    yield item

4.scrapy中item.py 中引入django模型類

 pip install scrapy-djangoitem
from app1 import models
from scrapy_djangoitem import DjangoItem

class AbckgItem(DjangoItem):
  # define the fields for your item here like:
  # name = scrapy.Field()      # 普通scrapy爬蟲寫法
  # title = scrapy.Field()
  # url = scrapy.Field()
  # content = scrapy.Field()
  django_model = models.ABCkg   # 注入django項(xiàng)目的固定寫法,必須起名為django_model =django中models.ABCkg表

5.pipelines.py中調(diào)用save()

import json
from pymongo import MongoClient
# 用于接收parse函數(shù)發(fā)過(guò)來(lái)的item
class AbckgPipeline(object):
  # i = 0
  def open_spider(self,spider):
    # print('打開文件')
    if spider.name == 'abckg':
      self.f = open('abckg.json',mode='w')
  def process_item(self, item, spider):
    # # print('ABC管道接收:{}'.format(item))
    # if spider.name == 'abckg':
    #   self.f.write(json.dumps(dict(item),ensure_ascii=False))
    # # elif spider.name == 'cctv':
    # #   img = requests.get(item['img'])
    # #   if img != '':
    # #     with open('圖片\%d.png'%self.i,mode='wb')as f:
    # #       f.write(img.content)
    # #   self.i += 1
    item.save()
    return item  # 將item傳給下一個(gè)管道執(zhí)行
  def close_spider(self,spider):
    # print('關(guān)閉文件')
    self.f.close()

6.在django中models.py中一個(gè)模型類,字段對(duì)應(yīng)爬取到的數(shù)據(jù),選擇適當(dāng)?shù)念愋团c長(zhǎng)度

class ABCkg(models.Model):
  title = models.CharField(max_length=30,verbose_name='標(biāo)題')
  url = models.CharField(max_length=100,verbose_name='網(wǎng)址')
  content = models.CharField(max_length=200,verbose_name='內(nèi)容')
  class Meta:
    verbose_name_plural = '爬蟲ABCkg'
  def __str__(self):
    return self.title

7.通過(guò)命令啟動(dòng)爬蟲:scrapy crawl 爬蟲名稱

8.django進(jìn)入admin后臺(tái)即可看到爬取到的數(shù)據(jù)。

到此這篇關(guān)于Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫(kù)的方法示例的文章就介紹到這了,更多相關(guān)Django Scrapy爬取數(shù)據(jù)入庫(kù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • python基于scrapy爬取京東筆記本電腦數(shù)據(jù)并進(jìn)行簡(jiǎn)單處理和分析
  • Scrapy元素選擇器Xpath用法匯總
  • python實(shí)現(xiàn)Scrapy爬取網(wǎng)易新聞
  • python爬蟲scrapy框架之增量式爬蟲的示例代碼
  • 一文讀懂python Scrapy爬蟲框架
  • Scrapy實(shí)現(xiàn)模擬登錄的示例代碼
  • Python爬蟲之教你利用Scrapy爬取圖片

標(biāo)簽:西安 天水 股票 白城 日照 錦州 隨州 安慶

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫(kù)的方法示例》,本文關(guān)鍵詞  Django,結(jié)合,使用,Scrapy,爬取,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫(kù)的方法示例》相關(guān)的同類信息!
  • 本頁(yè)收集關(guān)于Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫(kù)的方法示例的相關(guān)信息資訊供網(wǎng)民參考!
  • 企业400电话

    智能AI客服机器人
    15000

    在线订购

    合计11份范本:公司章程+合伙协议+出资协议+合作协议+股权转让协议+增资扩股协议+股权激励+股东会决议+董事会决议

    推薦文章