爬蟲采集下來的數據除了存儲在文本文件、excel之外,還可以存儲在數據集,如:Mysql,redis,mongodb等,今天辰哥就來教大家如何使用Python連接Mysql,並結合爬蟲為大家講解。
前提:這里默認大家已經安裝好mysql。
01 Mysql簡介
mysql是關系型數據庫,支持大型的數據庫,可以處理擁有上千萬條記錄的大型數據庫。通過爬蟲采集的數據集存儲到mysql后,可以借助mysql的關聯查詢將相關的數據一步取出。具體的作用這里就不贅述了,下面開始進入實際操作。
1.安裝pymysql
通過下面這個命令進行安裝
pip install pymysql
pymysql庫:Python3鏈接mysql
備注:
ps:MYSQLdb只適用於python2.x
python3不支持MYSQLdb,取而代之的是pymysql
運行會報:ImportError:No module named 'MYSQLdb'
2.python連接mysql
import pymysql as pmq
#connect(ip.user,password,dbname)
con = pmq.connect('localhost','root','123456','python_chenge')
#操作游標
cur = con.cursor()
localhost是本機ip,這里用localhost表示是當前本機,否則將localhost改為對應的數據庫ip。
root是數據庫用戶名,123456是數據庫密碼,python_chenge是數據庫名。
圖上的數據庫python_chenge已經建立好(建好之后,才能用上面代碼去連接),建好之后,當前是沒有表的,現在開始用Python進行建表,插入、查詢,修改,刪除等操作(結合爬蟲去講解)
02 建表
在存儲之前,先通過python創建表,字段有四個(一個主鍵+電影名稱,鏈接,評分)
# 創建 movie 表
movie_sql= '''
create table movie(
id int AUTO_INCREMENT primary key not null,
title varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci not null,
url varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci not null,
rate float not null
)
'''
# 執行sql語句
cur.execute(movie_sql)
# 提交到數據庫執行
con.commit()
創建表movie,字段分別為(id ,title ,url ,rate ),CHARACTER SET utf8 COLLATE utf8_general_ci是字符串編碼設置為utf8格式
id是主鍵primary key,int類型,AUTO_INCREMENT自增,非空not null
title,url 是字符串類型varchar(100),同樣非空
評分rate 是帶小數的數字,所以是float,同樣非空
03 插入數據
爬蟲已經采集到數據,python已經建好表,接着可以將采集的數據插入到數據庫,這里介紹兩種方式
### 插入數據
def insert(title,url,rate):
# 插入數據一
#cur.execute("INSERT INTO movie(title,url,rate) VALUES('"+str(title)+"','"+str(url)+"',"+str(rate)+")")
# 插入數據二
sql = "INSERT INTO movie(title,url,rate) VALUES('"+str(title)+"','"+str(url)+"',"+str(rate)+")"
cur.execute(sql)
# 提交到數據庫執行
con.commit()
id是自增的,所以不需要在傳值進去。
定義好插入數據庫方法后,開始往數據庫進行存儲
for i in json_data['subjects']:
insert(i['title'],i['url'],i['rate'])
04 查詢
1.查詢所有
查詢表中所有數據
# 查詢
cur.execute('select * from movie')
results = cur.fetchall()
for row in results:
Id = row[0]
title = row[1]
print("id=%s,title=%s" % (Id, title))
2.查詢指定的數據
比如查詢標題為:唐人街3這一條數據的所有字段
#查詢單條
cur.execute('select * from movie where title="唐人街探案3"')
results = cur.fetchall()
for row in results:
Id = row[0]
title = row[1]
url = row[2]
rate = row[3]
print("id=%s,title=%s,url=%s,rate=%s" % (Id, title,url,rate))
05 更新修改
更新數據,還是以上面:唐人街3為例,id為7,將唐人街3評分從5.5改為6
### 更新
def update():
sql = "update movie set rate='6' where Id = {0}".format(7)
cur.execute(sql)
con.commit()
同時看一下數據庫
06 刪除
同樣還是以唐人街為例,其id為7,刪除的話咱們可以更新id去刪除
def delete(Id):
sql = "delete from movie where Id = {0}".format(Id)
cur.execute(sql)
con.commit()
刪除之后,就沒有第7條數據了,說明刪除成功
07 小結
今天的技術講解文章就到此結束,主要是將了如何通過python去連接mysql,並進行建表,插入數據,查詢,更新修改和刪除。(干貨文章,推薦收藏)