环境:python3.6+django1.11+scrapy1.4+mysql5.7
实现思路:利用scrapy抓取到的数据存储到mysql,django做后端.
核心部分:需要用到scrapy-djangoitem这个库,利用django的orm,scrapy抓取到的数据直接存储到django的orm映射的mysql数据库中。
1、创建一个django工程<SeeMeizi>,再进入SeeMeizi工程中创建scrapy工程
scrapy startproject SeeMeiSpider
复制代码
2.、在django目录下新建static文件存放项目所需要的资源文件,然后在setting文件中对static路劲进行配置
3、创建django app,
Python manage.py startapp index
复制代码
为了后续扩展,在目录下创建个apps文件,存放所有创建的django app。
工程目录如上。
4、还需要在setting文件中配置apps的文件路劲,
接着是添加我们刚才创建的app到INSTALLED_APPS中去.
5、index下的models.py
from django.db import models
# Create your models here.
class Feeds(models.Model):
title = models.CharField(max_length=100, verbose_name='标题')
image_url = models.CharField(max_length=100, verbose_name='图片链接')
class Meta:
verbose_name = '动态'
verbose_name_plural = verbose_name
def __str__(self):
return self.title复制代码
Python manage.py makemigrations
Python manage.py migrate复制代码
6、接下来配置我们的scrapy项目中的setting文件,
import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'SeeMeiZi.settings'
django.setup()复制代码
这里是scrapy-djangoitem所需要的配置.
7、scrapy项目中的item文件
from scrapy_djangoitem import DjangoItem
from index.models import Feeds
class SeemeispiderItem(DjangoItem):
django_model = Feeds复制代码
8、scrapy项目中的pipline文件
class SeemeispiderPipeline(object):
def process_item(self, item, spider):
item.save()
return item复制代码
记得在setting文件中取消掉pipline的注释
9、在spiders文件夹下新建个MzSpider.py
from scrapy.spiders import CrawlSpider
from SeeMeiSpider.items import SeemeispiderItem
class MzSpider(CrawlSpider):
name = 'spider'
start_urls = ['http://www.lolmz.com/hot.php']
def parse(self, response):
img_list = response.xpath('//div[@class="chroma-gallery mygallery"]//img')
for img in img_list:
title = img.xpath('@alt').extract_first()
img_url = img.xpath('@src').extract_first()
item = SeemeispiderItem()
item['title'] = title
item['image_url'] = img_url
yield item复制代码
10、在新建个main.py运行我们的爬虫
from scrapy.cmdline import execute
execute('scrapy crawl spider'.split())复制代码
这样数据就抓到mysql中去了。
11、回到django项目中,index下的views.py
from django.shortcuts import render
from django.views.generic.base import View
from .models import Feeds
# Create your views here.
class FeedsView(View):
def get(self, request):
all_feeds = Feeds.objects.all()
return render(request, 'index.html', {'all_feeds': all_feeds})复制代码
12、index.html修改
13、最后在urls进行配置
from django.conf.urls import url
from django.contrib import admin
from index.views import FeedsView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', FeedsView.as_view(), name='index')
]复制代码
14、最后启动项目。
15、结束:大家还可以发挥更多的想象在拓展。