Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫(kù)的方法示例
在django項(xiàng)目根目錄位置創(chuàng)建scrapy項(xiàng)目,django_12是django項(xiàng)目,ABCkg是scrapy爬蟲(chóng)項(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.編寫(xiě)爬蟲(chóng),下面代碼以ABCkg為例,abckg.py
# -*- coding: utf-8 -*-
import scrapy
from ABCkg.items import AbckgItem
class AbckgSpider(scrapy.Spider):
name = 'abckg' #爬蟲(chóng)名稱
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爬蟲(chóng)寫(xiě)法 # title = scrapy.Field() # url = scrapy.Field() # content = scrapy.Field() django_model = models.ABCkg # 注入django項(xiàng)目的固定寫(xiě)法,必須起名為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('打開(kāi)文件')
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 = '爬蟲(chóng)ABCkg'
def __str__(self):
return self.title
7.通過(guò)命令啟動(dòng)爬蟲(chóng):scrapy crawl 爬蟲(chóng)名稱
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)文章希望大家以后多多支持腳本之家!
相關(guān)文章
YOLOv5車牌識(shí)別實(shí)戰(zhàn)教程(一)引言與準(zhǔn)備工作
這篇文章主要介紹了YOLOv5車牌識(shí)別實(shí)戰(zhàn)教程(一)引言與準(zhǔn)備工作,在這個(gè)教程中,我們將一步步教你如何使用YOLOv5進(jìn)行車牌識(shí)別,幫助你快速掌握YOLOv5車牌識(shí)別技能,需要的朋友可以參考下2023-04-04
Python實(shí)現(xiàn)聚類K-means算法詳解
這篇文章主要介紹了Python實(shí)現(xiàn)聚類K-means算法詳解,K-means(K均值)算法是最簡(jiǎn)單的一種聚類算法,它期望最小化平方誤差,具體詳解需要的朋友可以參考一下2022-07-07
python PIL Image 圖像處理基本操作實(shí)例
這篇文章主要介紹了python PIL Image 圖像處理基本操作實(shí)例包括圖片加載、灰度圖,圖像通道分離和合并,在圖像上輸出文字,圖像縮放,圖像閾值分割、 二值化,圖像裁剪需要的朋友可以參考下2022-04-04
Django用戶登錄與注冊(cè)系統(tǒng)的實(shí)現(xiàn)示例
這篇文章主要介紹了Django用戶登錄與注冊(cè)系統(tǒng)的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
Python使用cn2an實(shí)現(xiàn)中文數(shù)字與阿拉伯?dāng)?shù)字的相互轉(zhuǎn)換
這篇文章主要介紹了Python使用cn2an實(shí)現(xiàn)中文數(shù)字與阿拉伯?dāng)?shù)字的相互轉(zhuǎn)換,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
Python使用future處理并發(fā)問(wèn)題方案詳解
從Python3.2引入的concurrent.futures模塊,Python2.5以上需要在pypi中安裝futures包。future指一種對(duì)象,表示異步執(zhí)行的操作。這個(gè)概念的作用很大,是concurrent.futures模塊和asyncio包的基礎(chǔ)2023-02-02

