最近想通过爬取豆瓣数据来练习下爬虫,这次做一个爬取豆瓣书籍的信息。

需求:通过爬取豆瓣图书小说这一标签的数据,将数据存入csv或者数据库里面。

思路:先从网页上爬取数据,然后存到csv,然后读取csv的数据写到数据库中。(别问我为什么不直接写数据库,还要在csv中转一次。o(╯□╰)o。。。因为这个项目是逐渐练手的,是先写完csv,然后准备统计数据画图,所以想到还是存mysql好一点,就这样了。。。)

直接上个代码吧.。。。。。

画图表的方法还没完善,先上传上来,后面完善了再更

——————————————————————————————————————————————————

更新画图

# -*- coding: utf-8 -*-

'''

Created on 2018年8月17日

@author: zww

'''

import requests

import re

import random

import time

from lxml import etree

import pandas as pd

import matplotlib.pyplot as plt

import pymysql

from pymysql import charset

import csv

import codecs

# rating_list:评分, pl_list:评论人数

title_list, pub_list, rating_list, pl_list = [], [], [], []

def scrapy_contents(currentPage):

headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'}

cookies = {

'cookies': '这里弄成自己的cookies'}

url = ''.join(['https://book.douban.com/tag/小说?start=',

str((currentPage + 1) * 20), '&type=T'])

res = requests.get(url, headers=headers, cookies=cookies)

res.encoding = "utf-8"

if (res.status_code == 200):

print('\n第{}页的数据爬取成功'.format(currentPage))

print(url)

else:

print('\n o(╯□╰)o第{}页的数据爬取失败'.format(currentPage))

print(url)

x = etree.HTML(res.text)

# 豆瓣每一页有20条数据

for i in range(1, 21):

title = x.xpath(

'//*[@id="subject_list"]/ul/li[{}]/div[2]/h2/a/@title'.format(i))

pub = x.xpath(

'//*[@id="subject_list"]/ul/li[{}]/div[2]/div[1]/text()'.format(i))

rating = x.xpath(

'//*[@id="subject_list"]/ul/li[{}]/div[2]/div[2]/span[2]/text()'.format(i))

pl = x.xpath(

'//*[@id="subject_list"]/ul/li[{}]/div[2]/div[2]/span[3]/text()'.format(i))

# 遇到有一页只有19条数据。。。。

try:

title_list.append(str(title[0]).strip())

pub_list.append(str(pub[0]).strip())

rating_list.append(str(rating[0]))

# 抓出来的数据是: (13376人评价),这里只取数字

num = re.findall(r"\d+", str(pl[0]))

pl_list.append(num[0])

except Exception as e:

print('第%d条记录获取数据失败' % i)

print(e)

continue

def draw_chart(name_list, num_list, title=u'评分比例'):

plt.bar(range(len(num_list)), num_list,

tick_label=name_list, facecolor='#ff9999', edgecolor='white', )

plt.title(title)

plt.savefig(u'图书评分的柱状图') # 保存

plt.show()

def draw_pie(name_list, num_list, title=u'评分比例'):

plt.title(title)

# 正圆

plt.axes(aspect='equal')

# patches, l_texts, p_texts,为了得到饼图的返回值,p_texts饼图内部文本的,l_texts饼图外label的文本

patches, l_text, p_text = plt.pie(

num_list, labels=name_list, autopct='%1.1f%%',

pctdistance=0.8, textprops={'fontsize': 6, 'color': 'k'}, radius=1)

plt.savefig(u'图书评分的饼图') # 保存

plt.show()

def save_file(filename):

infos = {'书名': title_list, '出版信息': pub_list,

'评分': rating_list, '评论人数': pl_list}

data = pd.DataFrame(

infos, columns=['书名', '出版信息', '评分', '评论人数'])

data.to_csv(filename, index=False)

def insert(cur, sql, args):

cur.execute(sql, args)

def get_conn(host, port, user, passwd, db):

conn = pymysql.connect(

host=host, port=port, user=user, passwd=passwd, db=db, charset='utf8')

return conn

def query(cur, sql):

cur.execute(sql)

result = cur.fetchall()

return result

def read_csv_to_mysql(filename):

with codecs.open(filename=filename, mode='r', encoding='utf-8') as f:

reader = csv.reader(f)

head = next(reader)

conn = get_conn(

'localhost', 3306, 'root', '123456', 'test_scrapy')

cur = conn.cursor()

sql = '''insert into novel(BookName,Pub,Score,CommentNum) values(%s,%s,%s,%s)'''

for item in reader:

args = tuple(item)

insert(cur, sql=sql, args=args)

conn.commit()

cur.close()

conn.close()

def Drawing(name_list, num_list):

plt.rcParams['figure.figsize'] = (12, 8) # 设置图片的大小1200*800

plt.rcParams['font.sans-serif'] = ['SimHei'] # 这两句是为了显示中文不乱码

plt.rcParams['font.family'] = 'sans-serif'

draw_chart(name_list, num_list)

# draw_pie(name_list, num_list)

def main(scrapyPage):

for i in range(1, scrapyPage + 1):

scrapy_contents(i)

# 随机等待时间,免得被封ip

time.sleep(round(random.uniform(1, 2), 2))

now = time.strftime('%Y-%m-%d %H-%M-%S', time.localtime())

filename = now + "豆瓣图书评分信息.csv"

save_file(filename)

print('scrapy done!')

# 写到mysql里面

read_csv_to_mysql(filename)

if __name__ == '__main__':

main(48)

conn = get_conn(

'localhost', 3306, 'root', '123456', 'test_scrapy')

cur = conn.cursor(pymysql.cursors.DictCursor) # 字典形式返回

cur_list = conn.cursor() # 元组形式返回

sql = '''SELECT DISTINCT(Score) from novel ORDER BY Score desc'''

Scores = query(cur_list, sql)

Scores_num = {}

for i in Scores:

sql = 'SELECT count(*) as c from novel where Score =%s' % i

num = query(cur, sql)

num_value = num[0]['c']

num_key = str(i[0])

Scores_num[num_key] = num_value

name_list = list(Scores_num.keys())

num_list = list(Scores_num.values())

cur.close()

cur_list.close()

conn.close()

Drawing(name_list, num_list)

python爬取豆瓣书籍_python爬取豆瓣书籍排行相关推荐

  1. python爬取豆瓣书籍_Python 爬取豆瓣读书标签下的书籍

    这几天想爬下豆瓣读书时发现 github 上他人分享的源码都有一定年份了,豆瓣读书的页面貌似也稍微改了,于是就在前人轮子的基础上改进一下重新爬下豆瓣读书.Python 版本是 3.7. 1.爬取信息 ...

  2. python爬取豆瓣书籍_python 爬取豆瓣书籍信息

    继爬取 猫眼电影TOP100榜单 之后,再来爬一下豆瓣的书籍信息(主要是书的信息,评分及占比,评论并未爬取).原创,转载请联系我. 需求:爬取豆瓣某类型标签下的所有书籍的详细信息及评分 语言:pyth ...

  3. python 柱状图上显示字体_Python爬取百部电影数据,我发现了这个惊人真相!

    2019年就这么匆匆过去了,就在前几天国家电影局发布了2019年中国电影市场数据,数据显示去年总票房为642.66亿元,同比增长5.4%:国产电影总票房411.75亿元,同比增长8.65%,市场占比 ...

  4. python抓取微博评论_Python爬取新浪微博评论数据,你有空了解一下?

    开发工具 Python版本:3.6.4 相关模块: argparse模块: requests模块: jieba模块: wordcloud模块: 以及一些Python自带的模块. 环境搭建 安装Pyth ...

  5. python爬取手机微信_Python爬取微信好友

    前言 今天看到一篇好玩的文章,可以实现微信的内容爬取和聊天机器人的制作,所以尝试着实现一遍,本文记录了实现过程和一些探索的内容 itchat安装 对微信的控制可以使用itchat来实现,我们找到itc ...

  6. python开源代码百度盘_python爬取百度云网盘资源-源码

    今天测试用了一下python爬取百度云网盘资源. 代码片段import urllib import urllib.request import webbrowser import re def yun ...

  7. python爬取动态网页_python爬取动态网页数据,详解

    原理:动态网页,即用js代码实现动态加载数据,就是可以根据用户的行为,自动访问服务器请求数据,重点就是:请求数据,那么怎么用python获取这个数据了? 浏览器请求数据方式:浏览器向服务器的api(例 ...

  8. python爬关键词百度指数_Python 抓取指定关键词的百度指数

    百度指数很多时候在我们做项目的时候会很有帮助,从搜索引擎的流量端给到我们一些帮助,比如:家具行业的销量跟"装修","新房","二手房"等关键 ...

  9. python爬取豆瓣短评_Python爬取豆瓣指定书籍的短评

    Python爬取豆瓣指定书籍的短评 #!/usr/bin/python # coding=utf-8 import re import sys import time import random im ...

  10. python爬豆瓣top250书籍_Python——爬取目标豆瓣图书TOP250

    目标网址:https://book.douban.com/top250?start=0 导入模块: import requests from bs4 import BeautifulSoup 添加he ...

最新文章

  1. 关于Oracle组件如何正确实现动态Web的数据库
  2. 解决ERROR 2003 (HY000): Can't connect to MySQL server on
  3. CTFshow 爆破 web28
  4. 中国和英国的在学生创业环境上的区别
  5. 多iframe下的html同名id,获得同级iframe页面的指定ID元素的几种实现方法
  6. BadgerDAO锁仓量超过9亿美元
  7. 对前后端分离和FastDFS的使用的再理解
  8. https端口号_Wireshark使用以及https
  9. 【机器学习系列】变分推断第一讲:Variational Inference背景和用途
  10. android绘图软件推荐,动漫绘画辅助软件有哪些-7款绘画软件推荐
  11. mamp安装php扩展,mac版mamp下php安装pcntl扩展
  12. 如何用产品经理思维写一篇商业计划书
  13. T9 PDF如何转存为高清图片
  14. 信息录入率百分百上海强化施工现场建筑工人实名制管理
  15. Ada的故事(转载)
  16. 华为---ACL配置
  17. 判断某整数是否既是5又是7的整数倍()
  18. YOLOv5 + Tesseract-OCR 实现车牌号文本识别
  19. AppCube快速开发问卷调查应用在WeLink发布上线
  20. 计算机控制闪光灯,并联控制式自动调光闪光灯 - 最全的照相机闪光灯电路图大全(十款照相机闪光灯电路图详解)...

热门文章

  1. jenkins发送构建邮件配置项中文
  2. 使用截图工具FastStone Capture
  3. Fun with Opterons, SATA, and INNODB
  4. ant基本命令和使用
  5. Linux中KVM虚拟机是什么
  6. 数据结构 http://www.cnblogs.com/sun-haiyu/p/7704654.html
  7. 八叶一刀流·三之型·业炎击团队
  8. linux下查找文件、排序、查看文件内容
  9. Windows环境bugfree搭建
  10. android内核调试的步骤