脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Django结合使用Scrapy爬取数据入库的方法示例

Django结合使用Scrapy爬取数据入库的方法示例

2021-09-26 00:26shiguanggege Python

这篇文章主要介绍了Django结合使用Scrapy爬取数据入库的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

在django项目根目录位置创建scrapy项目,django_12是django项目,abckg是scrapy爬虫项目,app1是django的子应用

Django结合使用Scrapy爬取数据入库的方法示例

2.在scrapy的settings.py中加入以下代码

?
1
2
3
4
5
6
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# -*- 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('返回内容:{}'.format(response))
    """
    解析函数
    :param response: 响应内容
    :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('内容为:{}'.format(item))
    yield item

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

?
1
pip install scrapy-djangoitem
?
1
2
3
4
5
6
7
8
9
10
from app1 import models
from scrapy_djangoitem import djangoitem
 
class abckgitem(djangoitem):
  # define the fields for your item here like:
  # name = scrapy.field()      # 普通scrapy爬虫写法
  # python" id="highlighter_362789">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import json
from pymongo import mongoclient
# 用于接收parse函数发过来的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传给下一个管道执行
  def close_spider(self,spider):
    # print('关闭文件')
    self.f.close()

6.在django中models.py中一个模型类,字段对应爬取到的数据,选择适当的类型与长度

?
1
2
3
4
5
6
7
8
class abckg(models.model):
  title = models.charfield(max_length=30,verbose_name='标题')
  url = models.charfield(max_length=100,verbose_name='网址')
  content = models.charfield(max_length=200,verbose_name='内容')
  class meta:
    verbose_name_plural = '爬虫abckg'
  def __str__(self):
    return self.title

7.通过命令启动爬虫:scrapy crawl 爬虫名称

8.django进入admin后台即可看到爬取到的数据。

到此这篇关于django结合使用scrapy爬取数据入库的方法示例的文章就介绍到这了,更多相关django scrapy爬取数据入库内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/shiguanggege/article/details/114279146

延伸 · 阅读

精彩推荐