濮阳杆衣贸易有限公司

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

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

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

在django項目根目錄位置創(chuàng)建scrapy項目,django_12是django項目,ABCkg是scrapy爬蟲項目,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'  # 項目名.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/'] # 第一次請求的地址
  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})
    # 獲取下一頁
    nextpage = response.xpath('//*[@id="container"]/div[1]/div[10]/a[last()]/@href').extract_first()
    print('即將請求:{}'.format(nextpage))
    yield scrapy.Request(url=nextpage,callback=self.parse,method='GET',dont_filter=True)
    # 獲取詳情頁
  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項目的固定寫法,必須起名為django_model =django中models.ABCkg表

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

import json
from pymongo import MongoClient
# 用于接收parse函數(shù)發(fā)過來的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傳給下一個管道執(zhí)行
  def close_spider(self,spider):
    # print('關(guān)閉文件')
    self.f.close()

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

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.通過命令啟動爬蟲:scrapy crawl 爬蟲名稱

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

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

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

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

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫的方法示例》,本文關(guān)鍵詞  Django,結(jié)合,使用,Scrapy,爬取,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫的方法示例》相關(guān)的同類信息!
  • 本頁收集關(guān)于Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫的方法示例的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    盱眙县| 廉江市| 万山特区| 白山市| 耿马| 呼伦贝尔市| 富源县| 电白县| 德化县| 盐城市| 集安市| 紫金县| 榆社县| 区。| 大庆市| 浏阳市| 马龙县| 时尚| 怀柔区| 汕头市| 嫩江县| 桐庐县| 樟树市| 洛扎县| 和顺县| 文安县| 铜陵市| 石台县| 江山市| 伊春市| 张家川| 堆龙德庆县| 昔阳县| 岗巴县| 莆田市| 新闻| 屏东市| 华宁县| 庆安县| 宜州市| 道真|