存储到mysql数据库

我们需要新的模块 pymysql

pip install pymysql
复制代码

创建数据库book_store

create database book_store character set utf8;
复制代码

创建category分类表, 包含id和分类名

use book_store;
create table category(id int primary key auto_increment, name varchar(255) not null
);
复制代码

创建数据表book, 包含id,分类id,图书名,价格, 还有外键

create table book(id int primary key auto_increment,cid int not null,title varchar(200) not null,price decimal(10,2) not null,foreign key(cid) references category(id)
);
复制代码
mysql> desc category;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(255) | NO   |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
mysql> desc book;
+-------+---------------+------+-----+---------+----------------+
| Field | Type          | Null | Key | Default | Extra          |
+-------+---------------+------+-----+---------+----------------+
| id    | int(11)       | NO   | PRI | NULL    | auto_increment |
| cid   | int(11)       | NO   | MUL | NULL    |                |
| title | varchar(200)  | NO   |     | NULL    |                |
| price | decimal(10,2) | NO   |     | NULL    |                |
+-------+---------------+------+-----+---------+----------------+
4 rows in set (0.02 sec)
复制代码

使用python把爬取的数据保存到数据库

原来的代码...

import requests
from bs4 import BeautifulSoup
soup = BeautifulSoup(requests.get('http://books.toscrape.com/').text,'html.parser')
with open('books.txt','w',encoding='utf8') as file:for i in soup.find('ul',class_='nav nav-list').find('ul').find_all('li'):file.write(i.text.strip()+'\n')res = requests.get("http://books.toscrape.com/"+i.find('a')['href'])res.encoding='utf8'soup = BeautifulSoup(res.text,'html.parser')for j in soup.find_all('li',class_="col-xs-6 col-sm-4 col-md-3 col-lg-3"):print(j.find('h3').find('a')['title'])file.write('\t"{}" {}\n'.format(j.find('h3').find('a')['title'],j.find('p',class_='price_color').text))
复制代码

进行一下注释和改进

import requests
from bs4 import BeautifulSoup
soup = BeautifulSoup(requests.get('http://books.toscrape.com/').text,'html.parser')
for i in soup.find('ul',class_='nav nav-list').find('ul').find_all('li'):category = i.text.strip() # 分类名print(category)res = requests.get("http://books.toscrape.com/"+i.find('a')['href'])res.encoding='utf8'soup = BeautifulSoup(res.text,'html.parser')for j in soup.find_all('li',class_="col-xs-6 col-sm-4 col-md-3 col-lg-3"):title = j.find('h3').find('a')['title'] # 图书名price = j.find('p',class_='price_color').text # 图书价格
复制代码

研究一下pymysql 的使用方法

shockerli.net/post/python…

创建mysql连接

import pymysql
connection = pymysql.connect(host='localhost',port=3306,user='root',password='root',db='demo',charset='utf8')
复制代码

生成游标, 执行sql语句...

# 获取游标
cursor = connection.cursor()# 创建数据表
effect_row = cursor.execute('''
CREATE TABLE `users` (`name` varchar(32) NOT NULL,`age` int(10) unsigned NOT NULL DEFAULT '0',PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
''')# 插入数据(元组或列表)
effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%s, %s)', ('mary', 18))# 插入数据(字典)
info = {'name': 'fake', 'age': 15}
effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%(name)s, %(age)s)', info)connection.commit()
复制代码

一次性执行多条sql语句

# 获取游标
cursor = connection.cursor()# 批量插入
effect_row = cursor.executemany('INSERT INTO `users` (`name`, `age`) VALUES (%s, %s) ON DUPLICATE KEY UPDATE age=VALUES(age)', [('hello', 13),('fake', 28),])connection.commit()
复制代码

获取自增id

cursor.lastrowid
复制代码

查询数据, 一条或者多条

# 执行查询 SQL
cursor.execute('SELECT * FROM `users`')
# 获取单条数据
cursor.fetchone()
# 获取前N条数据
cursor.fetchmany(3)
# 获取所有数据
cursor.fetchall()
复制代码

思路分析

代码拆解

面向对象的写法...

import requests
from bs4 import BeautifulSoup
import pymysql
class Spider():def __init__(self, base_url):self.base_url = base_urlself.db = Database('localhost', 'root', 'root', 'book_store')self.soup = BeautifulSoup(requests.get(self.base_url).text, 'html.parser')def get_category(self):for i in self.soup.find('ul', class_='nav nav-list').find('ul').find_all('li'):category = i.text.strip()  # 分类名self.db.add_category(category)self.db.book_link_dict[category] = "http://books.toscrape.com/"+i.find('a')['href']def get_book(self):for cat in self.db.book_link_dict:res = requests.get(self.db.book_link_dict[cat])res.encoding = 'utf8'soup = BeautifulSoup(res.text, 'html.parser')for j in soup.find_all('li', class_="col-xs-6 col-sm-4 col-md-3 col-lg-3"):title = j.find('h3').find('a')['title']  # 图书名price = j.find('p', class_='price_color').text[1:]  # 图书价格self.db.add_book(cat, title, price)def start(self):self.get_category()self.get_book()
class Database():category_dict = {}book_link_dict = {}def __init__(self, host, username, password, db):self.connect = pymysql.connect(host=host, port=3306, user=username, password=password, db=db, charset='utf8')self.cursor = self.connect.cursor()def add_category(self, name):sql = "insert into `category`(`name`) values('{}')".format(name)print(sql)self.cursor.execute(sql)self.connect.commit()last_id = self.cursor.lastrowidself.category_dict[name] = last_idreturn last_iddef add_book(self, category, title, price):if category in self.category_dict:cid = self.category_dict[category]else:cid = self.add_category(category)sql = "insert into `book`(`cid`,`title`,`price`) values({},{},{})".format(cid, repr(title), price)print(sql)self.cursor.execute(sql)self.connect.commit()return self.cursor.lastrowid
if __name__ == "__main__":spider = Spider('http://books.toscrape.com/')spider.start()
复制代码

小作业:爬取猫眼电影top100, 保存 电影名, 排名, 评分, 主演, 封面图片, 上映时间到数据库

maoyan.com/board/4

快速跳转:

猫哥教你写爬虫 000--开篇.md
猫哥教你写爬虫 001--print()函数和变量.md
猫哥教你写爬虫 002--作业-打印皮卡丘.md
猫哥教你写爬虫 003--数据类型转换.md
猫哥教你写爬虫 004--数据类型转换-小练习.md
猫哥教你写爬虫 005--数据类型转换-小作业.md
猫哥教你写爬虫 006--条件判断和条件嵌套.md
猫哥教你写爬虫 007--条件判断和条件嵌套-小作业.md
猫哥教你写爬虫 008--input()函数.md
猫哥教你写爬虫 009--input()函数-人工智能小爱同学.md
猫哥教你写爬虫 010--列表,字典,循环.md
猫哥教你写爬虫 011--列表,字典,循环-小作业.md
猫哥教你写爬虫 012--布尔值和四种语句.md
猫哥教你写爬虫 013--布尔值和四种语句-小作业.md
猫哥教你写爬虫 014--pk小游戏.md
猫哥教你写爬虫 015--pk小游戏(全新改版).md
猫哥教你写爬虫 016--函数.md
猫哥教你写爬虫 017--函数-小作业.md
猫哥教你写爬虫 018--debug.md
猫哥教你写爬虫 019--debug-作业.md
猫哥教你写爬虫 020--类与对象(上).md
猫哥教你写爬虫 021--类与对象(上)-作业.md
猫哥教你写爬虫 022--类与对象(下).md
猫哥教你写爬虫 023--类与对象(下)-作业.md
猫哥教你写爬虫 024--编码&&解码.md
猫哥教你写爬虫 025--编码&&解码-小作业.md
猫哥教你写爬虫 026--模块.md
猫哥教你写爬虫 027--模块介绍.md
猫哥教你写爬虫 028--模块介绍-小作业-广告牌.md
猫哥教你写爬虫 029--爬虫初探-requests.md
猫哥教你写爬虫 030--爬虫初探-requests-作业.md
猫哥教你写爬虫 031--爬虫基础-html.md
猫哥教你写爬虫 032--爬虫初体验-BeautifulSoup.md
猫哥教你写爬虫 033--爬虫初体验-BeautifulSoup-作业.md
猫哥教你写爬虫 034--爬虫-BeautifulSoup实践.md
猫哥教你写爬虫 035--爬虫-BeautifulSoup实践-作业-电影top250.md
猫哥教你写爬虫 036--爬虫-BeautifulSoup实践-作业-电影top250-作业解析.md
猫哥教你写爬虫 037--爬虫-宝宝要听歌.md
猫哥教你写爬虫 038--带参数请求.md
猫哥教你写爬虫 039--存储数据.md
猫哥教你写爬虫 040--存储数据-作业.md
猫哥教你写爬虫 041--模拟登录-cookie.md
猫哥教你写爬虫 042--session的用法.md
猫哥教你写爬虫 043--模拟浏览器.md
猫哥教你写爬虫 044--模拟浏览器-作业.md
猫哥教你写爬虫 045--协程.md
猫哥教你写爬虫 046--协程-实践-吃什么不会胖.md
猫哥教你写爬虫 047--scrapy框架.md
猫哥教你写爬虫 048--爬虫和反爬虫.md
猫哥教你写爬虫 049--完结撒花.md

转载于:https://juejin.im/post/5cfc4adcf265da1b70049b74

猫哥教你写爬虫 039--存储数据相关推荐

  1. 猫哥教你写爬虫 046--协程-实践-吃什么不会胖

    吃什么不会胖? 低热量食物 食物的数量有千千万,如果我们要爬取食物热量的话,这个数据量必然很大. 使用多协程来爬取大量的数据是非常合理且明智的选择 如果我们要爬取的话,那就得选定一个有存储食物热量信息 ...

  2. 猫哥教你写爬虫 006--条件判断和条件嵌套

    流程控制 复仇者联盟3-无限战争(搜集宝石) python里面, 不需要使用;来结尾, 因为python是使用换行来结束一行代码的 if判断, 没有{}, python使用缩进来表示层级关系 if.. ...

  3. 猫哥教你写爬虫 002--作业-打印皮卡丘

    作业 请你使用print()函数将下面的皮卡丘打印出来, 使用三种方式 へ /|/\7 ∠_// │ / /│ Z _,< / /`ヽ│ ヽ / 〉Y ` / /イ● 、 ● ⊂⊃〈 /() へ ...

  4. 猫哥教你写爬虫 005--数据类型转换-小作业

    小作业 程序员的一人饮酒醉 请运用所给变量,使用**str()**函数打印两句话. 第一句话:1人我编程累, 碎掉的节操满地堆 第二句话:2眼是bug相随, 我只求今日能早归 number1 = 1 ...

  5. 猫哥教你写爬虫 004--数据类型转换-小练习

    小练习, 改一下代码 word = '3.8' number = 1 sentence = '人工智障说:3.8+1等于' print(sentence+str(int(float(word)+num ...

  6. 猫哥教你写爬虫 037--爬虫-宝宝要听歌

    戴上耳机, 这个世界与我无关... 让我们用音乐洗涤心灵吧... 我们从哪个网站爬取资源呢? 专治各种不服... 打开酷狗官网, 可以看到搜索框,我们要爬取的数据就是搜索歌曲后, 酷狗后台返回的歌曲列 ...

  7. 猫哥教你写爬虫 027--模块介绍

    time模块 import time # 时间对象转美式时间字符串 print(time.asctime()) # Wed May 29 09:25:07 2019 print(time.asctim ...

  8. 猫哥教你写爬虫 000--开篇

    写在前面 快速跳转: 猫哥教你写爬虫 000--开篇.md 猫哥教你写爬虫 001--print()函数和变量.md 猫哥教你写爬虫 002--作业-打印皮卡丘.md 猫哥教你写爬虫 003--数据类 ...

  9. OpenGL.Shader:志哥教你写一个滤镜直播客户端:仿3个抖音滤镜效果(4镜像/电击/灵魂出窍)

    OpenGL.Shader:志哥教你写一个滤镜直播客户端(可能是结束篇) OpenGL.Shader基本的图像处理知识已经学习的7788了,所以这篇应该是滤镜直播客户端的最后一篇了,之后会出基于FFm ...

  10. OpenGL.Shader:志哥教你写一个滤镜直播客户端(5)视觉滤镜:对比度、曝光、马赛克

    OpenGL.Shader:志哥教你写一个滤镜直播客户端(5) 上一章介绍了如何在渲染nv21流的时候进行滤镜的无缝切换,这章内容紧接上一章,介绍三种滤镜特效:对比度.曝光.马赛克,并介绍如何动态调节 ...

最新文章

  1. 【c语言】求两数之和
  2. 硬件框图分析、核心元器件参数选定和核心元器件参数选择
  3. 【LeetCode从零单排】No19.RemoveNthNodeFromEndofList
  4. ABAP更改程序的请求包操作
  5. VTK:绘制BorderPixelSize边框像素大小用法实战
  6. boost::fusion::all用法的测试程序
  7. 大型网站技术架构03
  8. upload file more than 4MB
  9. 图文:详解数据库Oracle 11g的基本安装
  10. C++primer plus第六版课后编程题答案 6.6
  11. 关于阿里云,有什么故事?
  12. 商用型虚拟试衣技术亮相CES Asia ,好买衣携手CA催生服装新零售变革
  13. 可以观看CCTV-5高清直播的网站-天天直播
  14. SPI协议(一):读SPI_Flash(M25P16)设备ID
  15. Advanced Computer Network Review(4)——Congestion Control of MPTCP
  16. 古代奥运会创始人是谁?
  17. PS如何修改gif动图 播放速度 - 本地方法篇
  18. 更改会话语言oracle,alter session 修改的参数值在会话中如何回退
  19. Excel VBA:数据管理与维护
  20. 被迫毕业,面试 30 家公司,终于上岸了!

热门文章

  1. Logstash:从grok到5.X版本的dissect
  2. oracle资产中fa_deprn_summary存储内容,关于FA的YTD Deprn的一个问题
  3. 计算机主机可以有几个硬盘,一台电脑可以安装盘几个硬盘?
  4. 简单好用的桌面日历便签软件有哪些?
  5. 解决Mybatis报错问题:Type interface com.tjcu.dao.UserDao is not known to the MapperRegistry.
  6. 基于Python+网络爬虫的兼职招聘就业信息数据可视化分析
  7. Bzoj1208 宠物收养所
  8. 朱啸虎的“合并盈利论”,实为ofo抢道摩拜带节奏
  9. python创建列表以及列表的操作(插入-删除-索引-交换元素值-切片)
  10. 在线正则表达式测试器(JavaScript)