python系列之(3)爬取豆瓣图书数据

上次介绍了beautifulsoup的使用,那就来进行运用下吧。本篇将主要介绍通过爬取豆瓣图书的信息,存储到sqlite数据库进行分析。

1.sqlite

SQLite是一个进程内的库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。它是一个零配置的数据库,这意味着与其他数据库一样,您不需要在系统中配置。

就像其他数据库,SQLite 引擎不是一个独立的进程,可以按应用程序需求进行静态或动态连接。SQLite 直接访问其存储文件。

在Mac是自带sqlite的,不需要重新安装,它的语法也和mysql很像,但存储的是文本文件的格式。下边简单介绍下使用。

创建数据库

sqlite3 spider.db

查看数据库

sqlite> .databases
main: /Users/kumufengchun/Documents/python/douban/spider.db

创建数据表,我们把爬取的数据表存储到douban的表里,结构如下

CREATE TABLE douban(
   id  integer PRIMARY KEY autoincrement     NOT NULL,
   tag            VARCHAR(50)    NOT NULL,
   title           VARCHAR(50)    NOT NULL,
   author       VARCHAR(50) NOT NULL,
   price         NUMERIC NOT NULL,
   rating        NUMERIC NOT NULL,
   number         INTEGER(10) NOT NULL,
   pub_info        TEXT NOT NULL
);

查看数据表结构

sqlite> .schema douban
CREATE TABLE douban(
   id  integer PRIMARY KEY autoincrement     NOT NULL,
   tag            VARCHAR(50)    NOT NULL,
   title           VARCHAR(50)    NOT NULL,
   author       VARCHAR(50) NOT NULL,
   price         NUMERIC NOT NULL,
   rating        NUMERIC NOT NULL,
   number         INTEGER(10) NOT NULL,
   pub_info        TEXT NOT NULL
);

退出数据库

sqlite> .quit

好的,简单介绍就是上边把,如果想要了解更详细的用法,可以到菜鸟教程看,https://www.runoob.com/sqlite/sqlite-intro.html

2.python爬取代码

import sys
import time
import urllib3
import requests
import numpy as np
import sqlite3
from bs4 import BeautifulSoup
from urllib import parse

headers=[{'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'},\
{'User-Agent':'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11'},\
{'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'}]

def do_spider(book_tag_lists):
    for book_tag in book_tag_lists:
        book_spider(book_tag)

def book_spider(book_tag):
    page_num = 0;
    page_size = 20
    total_size = 0;
    while(1):
        url = "https://book.douban.com/tag/"+parse.quote(book_tag)+"?start="+str(page_num*page_size)+"&type=T"
        print(url)
        http = urllib3.PoolManager()
        time.sleep(np.random.rand()*5)
        try:
            r = http.request("GET", url, headers=headers[page_num%len(headers)])
            plain_text = r.data.decode()
            print(plain_text)
        except Exception as e:
            print(e)
            continue
 
        soup = BeautifulSoup(plain_text, features="lxml")
        ligroup = soup.find_all("li", class_="subject-item")
        
        for item in ligroup:
            try:
                name = list(item.find("div", class_="info").a.stripped_strings)
                title = name[0]
                pubinfo = item.find("div", class_="pub").string.strip().split("/")
                author = pubinfo[0]
                price = pubinfo[-1]
                pubinfo = pubinfo[-3]
                commentnumber = list(filter(str.isdigit, item.find("span", class_="pl").string))
                number = ''.join(commentnumber)
                rating = item.find("span", class_="rating_nums").string.strip()
                add_record(book_tag, title, author, price, number, rating, pubinfo)
            except Exception as e:
                print(e)
                continue
        page_num+=1
        total_size+=page_size
        if total_size > 100:
            break

def add_record(tag, title, author, price, commentnumber, rating, pubinfo):
    conn = sqlite3.connect("spider.db")
    cursor = conn.cursor()
    cursor.execute("insert into douban values (null, ?, ?, ?, ?, ?, ?, ?)", (tag, title, author, price, rating,  commentnumber,  pubinfo))
    cursor.close()
    conn.commit()
    conn.close()


if __name__=='__main__':
    book_tag_lists=['传记', '职场', '管理', '互联网', '经典']
    book_result=do_spider(book_tag_lists)

3.查询分析

上述代码执行完,就会在数据库中存储数据,我们可以像查询mysql那样来查询分析。

查询总条数

sqlite> select count(1) from douban;
879

查询评分9.5以上的

sqlite> select * from douban where rating > 9.5;
10|小说|红楼梦|[清] 曹雪芹 著、高鹗 续 | 59.70元|9.6|235724| 人民文学出版社
71|金融|金融经济学二十五讲|徐高 |52|9.7|94| 中国人民大学出版社有限公司
98|金融|经济学原理|N.格里高利•曼昆 | 64.00元|9.6|1611| 北京大学出版社
177|计算机|深入理解计算机系统(原书第3版)|Randal E.Bryant、David O'Hallaron | 139.00元|9.7|802| 机械工业出版社
187|计算机|深入理解计算机系统(原书第2版)|(美)Randal E.Bryant、David O'Hallaron | 99.00元|9.7|2403| 机械工业出版社
195|计算机|数据密集型应用系统设计|Martin Kleppmann |128|9.7|253| 中国电力出版社
213|计算机|具体数学|Ronald L.Graham、Oren Patashnik、Donald E.Knuth | 99.00元|9.6|280| 人民邮电出版社
249|历史|20世纪思想史|[英] 彼得·沃森 |248|9.6|108| 译林出版社
275|历史|西方哲学史(第9版)|[美] 撒穆尔·伊诺克·斯通普夫、[美] 詹姆斯·菲泽 | 99.80元|9.7|193| 后浪丨北京联合出版公司
279|历史|艺术的故事|[英] 贡布里希 (Sir E.H.Gombrich) |280|9.6|11761| 广西美术出版社
361|传记|拿破仑传|埃米尔・路德维希 |68|9.6|126| 江西人民出版社
390|传记|纳博科夫传|[新西兰]布赖恩·博伊德 | 158.00元(全二册)|9.6|22| 广西师范大学出版社
401|传记|希特勒|伊恩·克肖 (Ian Kershaw) | CNY 168.00|9.6|31| 世界知识出版社
762|经典|红楼梦|[清] 曹雪芹 著、高鹗 续 | 59.70元|9.6|235729| 人民文学出版社
867|经典|西方哲学史(第9版)|[美] 撒穆尔·伊诺克·斯通普夫、[美] 詹姆斯·菲泽 | 99.80元|9.7|193| 后浪丨北京联合出版公司
877|经典|艺术的故事|[英] 贡布里希 (Sir E.H.Gombrich) |280|9.6|11761| 广西美术出版社

查询每个tag的数量

sqlite> select tag,count(1) from douban group by tag;
互联网|118
传记|118
历史|67
小说|40
科幻|17
管理|120
经典|120
职场|119
计算机|46
金融|114

查询每个作家的数量及大于3本的量的作家

sqlite> select author,count(1) from douban group by author having count(1)>3 order by count(1) desc;
吴军 |15
刘慈欣 |12
余华 |6
吴晓波 |6
金庸 |6
[哥伦比亚] 加西亚·马尔克斯 |5
[日] 东野圭吾 |5
[英] J. K. 罗琳 |5
当年明月 |5
陈忠实 |5
[日] 村上春树 |4
[美] 凯文·凯利 |4
[美] 彼得·德鲁克 |4
[美] 沃尔特·艾萨克森 |4
[英] 乔治·奥威尔 |4
张宏杰 |4
路遥 |4

等等,还可以查询其他的。

4.问题

为啥建了表却找不到?

进入到创建表的目录,然后执行 sqlite3 spider.db

python环境?

用的是python3.6版本

豆瓣网址?

https://book.douban.com/tag/%E6%96%87%E5%AD%A6

猜你喜欢

转载自www.cnblogs.com/kumufengchun/p/11935559.html
今日推荐