爬虫+Django框架|当当网Python热销书,你看过哪几本?

作者| GitPython

来源| GitPython

让我们换一种方式,看看当当网上python书的热销排行情况。

同时也看看,热销书中,你看过哪几本?

前60本中,

我的书单列表如下:

Top2-python编程 从入门到实践

Top10-码农翻身(好玩有趣的编程知识)

Top18-算法图解

Top19-Python编程快速上手 让繁琐工作自动化

Top39-Python深度学习

在现在的大背景下,所有的产品可能都会趋向于一个web项目,为用户提供服务。

近年来,引申出了很多web+的岗位,web+爬虫、web+数据分析、web+运维等。

本文带你从获取数据,到数据库的使用,到Django项目的搭建,以及最后的前端展示,完全跑通一个小型的Django项目。

所以,如果你想学学Django开发,这篇文章你一定不容错过。

1.效果展示

    

把当当网爬取下来的数据保存到Mysql数据库,再通过Django框架,把数据显示到前端。

2.编写思路

1)获取URL

进入当当网首页,以“python”为关键词,搜索图书,并按照“热销程度”进行排序。这样,我们就拿到了准备访问的URL地址。

2)发送请求,获取响应

import requests

url = 'http://search.dangdang.com/?key=python&act=input&category_path=01.00.00.00.00.00&type=01.00.00.00.00.00&sort_type=sort_sale_amt_desc'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0".3809.100 Safari/537.36',

}

response = requests.get(url,headers=headers)
print(response.text)

3)解析数据

xpath进行解析,获取我们想要的图书信息。

图书信息:

- 名称(title)

- 作者(author)

- 价格(price)

- 评分(star)

from lxml import etree
import re

html = etree.HTML(response.text)
div_list = html.xpath('//*[@id="component_59"]/li')

item_list = []

for div in div_list:
    # 遍历每一条信息
    item = {}

    # ./ 注意从当前节点,向下获取
    item['title'] = div.xpath('./a/@title')[0]
    item['price'] = div.xpath('./p[@class="price"]/span[@class="search_now_price"]/text()')[0]
    item['author'] = div.xpath('./p[@class="search_book_author"]//a/text()')[0]
    score = div.xpath('./p[@class="search_star_line"]/span/span/@style')[0]
    score_d = int(re.findall(r'\d+',score)[0])/20
    item['star'] = score_d
    item_list.append(item)

print(len(item_list))
print(item_list)

4)保存数据

与以往不同的是,数据保存到mysql数据库中。

import pymysql
# 1.先在自己的电脑上,安装好mysql数据库,并建立一个名为"book"的数据库
# 2.建立连接,创建游标

conn = pymysql.connect(host="127.0.0.1", user="root", passwd="123456", db="book")
cursor = conn.cursor()

for i,item in enumerate(item_list):

    print(item)
    a = item['title']
    b = item['author']
    c = item['star']
    d = item['price']
    # 3.编写sql语句,把获取的数据插入到book数据库下的book_book数据表中
    sql = "insert into book_book (id,title, author, star, price) values (%s, %s, %s, %s, %s)"
    try:
        cursor.execute(sql,(i, a, b, c, d))
        conn.commit()   # 4.执行sql语句
    except Exception as err:
        conn.rollback()
        print(err)

# 5.保存成功,断开连接
cursor.close()
conn.close()

  

5)Django框架

将前面实现的功能以web形式展示,后端框架选用Django。

整个Django项目的目录结构

dangdang
│  db.sqlite3
│  manage.py
│
├─book
│  │  admin.py
│  │  apps.py
│  │  models.py
│  │  tests.py
│  │  urls.py
│  │  views.py
│  │  __init__.py
│  │
│  ├─migrations
│  │  │  0001_initial.py
│  │  │  __init__.py
│  │  │
│  ├─templates
│  │      index.html
│  │
│
├─dangdang
│  │  settings.py
│  │  urls.py
│  │  wsgi.py
│  │  __init__.py
│  │

创建第一个Django项目

terminal 运行下面代码:

# 安装Django扩展库
pip install django

# 创建Django项目
django-admin startproject dangdang

# 创建应用
python manage.py startapp book

# 运行Django项目
python manage.py runserver

修改语言和时区

dangdang/setting.py

LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'

在浏览器中输入

http://127.0.0.1:8000

访问我们的服务器,效果如下图所示。

Django连接Mysql数据库

先来一下Django的MVT模式,

以及数据是怎么从数据库传到前端网页上展示出来的?

修改默认的数据库连接方式

dangdang/setting.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'book',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': 'localhost',
        'PORT': 3306
    }
}

下面这段代码的作用:

将PyMySQL视为MySQLdb来使用,从而避免Django找不到连接MySQL的客户端工具。

dangdang/__init__.py

import pymysql
pymysql.install_as_MySQLdb()

定义数据库的映射类

book/models.py

from django.db import models

class BOOK(models.Model):
    title = models.CharField(max_length=20)
    author = models.CharField(max_length=20)
    star = models.CharField(max_length=20)
    price = models.CharField(max_length=20)

生成迁移文件

terminal

python manage.py makemigrations
python manage.py migrate

前端展示

book/templates/index.html

{% if movies %}
    <h3 align="center" id="myheader">效果展示</h3>
    <table class="table table-striped" id="mytable">
        <thead>
        <tr>
            <th width="40%">Title</th>
            <th width="20%">Author</th>
            <th width="20%">Price</th>
            <th width="20%">Star</th>
        </tr>
        </thead>

        <tbody>
        {% for movie in movies %}
            <tr>
                <td>{{ movie.title }}</td>
                <td>{{ movie.author }}</td>
                <td>{{ movie.price }}</td>
                <td>{{ movie.star }}</td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
{% endif %}

3.依赖环境

- request爬虫

- xpath解析

- pymysql模块

- mysql数据库

- django框架

4.总结

关于Django框架,我推荐可以看网易云课堂上的一个免费课程。

Python之Django企业开发实战

https://study.163.com/course/courseMain.htm?courseId=1209164807

本文整体回顾

5.源码地址

https://github.com/hufe09/maoyan_top100

本文复用了该项目下的部分内容,已经过作者同意。

后台回复当当网

获取此项目相关的源代码。

往期精彩回顾

1.我是怎么批量下载百度图片的,当然是用python了!

2.爬取《哪吒》豆瓣短评,我得到了什么?

3.我是怎么保存公众号历史文章合集到本地的?

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值