前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >(爬虫)书籍和电影,程序员不可或缺爬虫步骤1. 分析目标网页的特征2. 找到需要爬取的数据3.多页面数据的跳转4.数据存储

(爬虫)书籍和电影,程序员不可或缺爬虫步骤1. 分析目标网页的特征2. 找到需要爬取的数据3.多页面数据的跳转4.数据存储

作者头像
若与
发布2018-04-25 14:32:00
6280
发布2018-04-25 14:32:00
举报

周五, 由于同事给了一个下载书籍的网站。所以心血来潮,想写一个爬虫demo,把数据都爬下来。然后发现一个电影网站也是类似,于是乎。代码重用。

爬虫步骤

  1. 分析目标网页的特征
  2. 找到需要爬取的数据
  3. 多页面数据的跳转
  4. 数据存储

1. 分析目标网页的特征

我今天要爬取的页面数据就是 周读, http://www.ireadweek.com/, 页面结构很简答,先是使用requests + bs4配合爬取。发现页面没有使用js,也没有做反爬虫的机制,所以很简单。

这个网站就两层结构, 主页->点击每个书籍->进入到书籍的详情页。我需要的数据也就是在详情页。如下图:

2. 找到需要爬取的数据

上图中标记的都是需要爬取的数据 使用bs4格式化数据,发现数据很容易获得,每个数据都很简单。页面标签修饰都没有,像class,id都没有,像是一个只会html的外行写的。我一个后端,也能笑话别人的页面_. 数据抽取的代码如下:

代码语言:javascript
复制
        html_doc = response.body
        soup = BeautifulSoup(html_doc, 'html.parser')

        img_url = urljoin(CDN, soup.find('img').attrs.get('src').replace('//','/'))
        download_url = soup.find('a', class_='downloads').attrs.get('href')
        title = soup.find_all('div', class_='hanghang-za-title')
        name = title[0].text

        content = soup.find_all('div', class_='hanghang-za-content')
        author_info = content[0].text
        directory = '\n'.join([i.text.replace("\u3000", '') for i in content[1].find_all('p')])

        info = soup.find('div', class_='hanghang-shu-content-font').find_all('p')

        author = info[0].text.split('作者:')[1]
        category = info[1].text.split('分类:')[1]
        score = info[2].text.split('豆瓣评分:')[1]
        introduction = info[4].text

3.多页面数据的跳转

这个主要是处理页面之间的跳转。就是使用下面的页码进行页面的跳转,我使用下一页

然后再抓取,继续迭代就可以了。

代码语言:javascript
复制
        next_url = urljoin(DOMAIN, soup.find_all('a')[-2].attrs.get('href'))
        yield scrapy.Request(next_url, callback=self.parse)

由于没有使用具体的id,class,只能使用位置索引。

4.数据存储

数据存储,以前都是写到excel中或redis中,今天想写到mysql中,写到mysql可以使用pymysql或mysqlDB。 我选择使用ORM。 可以是SQLALCHEMY, Django Model. 我选择的是django model.

代码语言:javascript
复制
# django中
from django.db import models


# Create your models here.
class Book(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=255)
    author = models.CharField(max_length=255)
    category = models.CharField(max_length=255)
    score = models.CharField(max_length=100)
    img_url = models.URLField()
    download_url = models.URLField()
    introduction = models.CharField(max_length=2048)
    author_info = models.CharField(max_length=2048)
    directory = models.CharField(max_length=4096)
    create_edit = models.DateTimeField(auto_now_add=True)

    class Meta:
        managed = False
        db_table = "ireadweek"

# scrapy settings.py配置
import os
import sys
import django

sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".."))
os.environ['DJANGO_SETTINGS_MODULE'] = 'Rino_nakasone_backend.settings'

django.setup()


# 在 scrapy中pipelines.py
from ireadweek.models import Book
import datetime


class RinonakasonePipeline(object):
    def process_item(self, item, spider):
        book = Book()
        book.name = item.get('name')
        book.author = item.get('author')
        book.category = item.get('category')
        book.score = item.get('score')
        book.image_url = item.get('image_url')
        book.download_url = item.get('download_url')
        book.introduction = item.get('introduction')
        book.author_info = item.get('author_info')
        book.directory = item.get('directory')
        book.create_edit = datetime.datetime.now()
        book.save()
        return item

# 在spider中引用

    def parse_news(self, response):
        item = IreadweekItem()
        html_doc = response.body
        soup = BeautifulSoup(html_doc, 'html.parser')

        img_url = urljoin(CDN, soup.find('img').attrs.get('src').replace('//','/'))
        download_url = soup.find('a', class_='downloads').attrs.get('href')
        title = soup.find_all('div', class_='hanghang-za-title')
        name = title[0].text

        content = soup.find_all('div', class_='hanghang-za-content')
        author_info = content[0].text
        directory = '\n'.join([i.text.replace("\u3000", '') for i in content[1].find_all('p')])

        info = soup.find('div', class_='hanghang-shu-content-font').find_all('p')

        author = info[0].text.split('作者:')[1]
        category = info[1].text.split('分类:')[1]
        score = info[2].text.split('豆瓣评分:')[1]
        introduction = info[4].text

        item['name'] = name
        item['img_url'] = img_url
        item['download_url'] = download_url
        item['author'] = author
        item['author_info'] = author_info
        item['category'] = category
        item['score'] = score
        item['introduction'] = introduction
        item['directory'] = directory

        return item

# 还有一个配置 settings.py
ITEM_PIPELINES = {
   'RinoNakasone.pipelines.RinonakasonePipeline': 300,
}

技术要点

  1. scrapy
  2. django
  3. beautifulsoup

以上都要会使用,我还写了一个api接口。 http://127.0.0.1:8080/api/ireadweek/list/?p=400&n=20

另外一个网站是:

我项目的地址: https://github.com/jacksonyoudi/Rino_nakasone_backend

代码都在项目中。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.03.25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 爬虫步骤
  • 1. 分析目标网页的特征
  • 2. 找到需要爬取的数据
  • 3.多页面数据的跳转
  • 4.数据存储
    • 技术要点
      • 另外一个网站是:
      相关产品与服务
      数据保险箱
      数据保险箱(Cloud Data Coffer Service,CDCS)为您提供更高安全系数的企业核心数据存储服务。您可以通过自定义过期天数的方法删除数据,避免误删带来的损害,还可以将数据跨地域存储,防止一些不可抗因素导致的数据丢失。数据保险箱支持通过控制台、API 等多样化方式快速简单接入,实现海量数据的存储管理。您可以使用数据保险箱对文件数据进行上传、下载,最终实现数据的安全存储和提取。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档