Python數據持久化存儲實現方法分析
本文實例講述了Python數據持久化存儲實現方法。分享給大家供大家參考,具體如下:
1、pymongo的使用
前三步為創(chuàng)建對象
- 第一步創(chuàng)建連接對象
conn = pymongo.MongoClient('IP地址',27017)
- 第二步創(chuàng)建庫
db = conn['庫名']
- 第三步創(chuàng)建表
myset = db['集合名']
- 第四步把數據插入數據庫
myset.inset.one({})
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2019/6/26 8:56
# @Author : #####
# @Site :
# @File : 貓眼電影_mongo存儲.py
# @Software: PyCharm
from urllib import request
import re
import time
import pymongo
class MaoyanSpider(object):
def __init__(self):
self.headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.5221.400 QQBrowser/10.0.1125.400'}
#用來計數
self.page=1
#連接對象
self.coon =pymongo.MongoClient('locslhost',27017)
#創(chuàng)建庫對象
self.db=self.coon['maoyaodb']
#集合對象
self.myset=self.db['top100']
def get_page(self,url):
req = request.Request(url,headers=self.headers)
res = request.urlopen(req)
html = res.read().decode('utf-8')
self.parse_page(html)
def parse_page(self,html):
p = re.compile( '<div class="movie-item-info">.*?title="(.*?)".*?class="star">(.*?)</p>.*?class="releasetime">(.*?)</p>',re.S)
r_list = p.findall(html)
self.write_mongo(r_list)
def write_mongo(self,r_list):
for r_t in r_list:
d={
'電影名稱:':r_t[0].strip(),
'電影主演:':r_t[1].strip(),
'上映時間:':r_t[2].strip()
}
#插入數據庫
self.myset.inset.one(d)
def work_on(self):
for pn in range(0,41,10):
url = 'https://maoyan.com/board/4?offset=%s' % str(pn)
self.get_page(url)
print('第%d頁爬取成功' % self.page)
self.page += 1
time.sleep(4)
if __name__ == '__main__':
begin = time.time()
spider = MaoyanSpider()
spider.work_on()
end = time.time()
print("執(zhí)行時間%.2f" % (end - begin)) #注不完美,仍然需修改
2、mysql的使用
Mysql-front可視化工具,建庫建表添加字段
1、創(chuàng)建連接對象:db = pymysql.connet
2、創(chuàng)建游標對象:cursor = db.sursor
3、執(zhí)行命令:cursor.execute()
4、提交到數據庫執(zhí)行
5、關閉:cursor.close
mysql-Front使用流程
1、創(chuàng)建數據庫:
localhost--數據庫--新建---數據庫
數據庫名改為maoyan (項目mysql庫名)--- 字符集utf8 ---確定
2、創(chuàng)建表:
流程:選中maoyao數據庫 --選中數據 ----新建 ----出現添加菜單 ---名稱改為top100 ---創(chuàng)建成功
3、往表格中添加字段:
流程:選中top100表單 --- 數據庫 ----新建 ----字段 ---出現添加界面 ----名稱改為name ---默認varchar ---- 長度50 --確定
用同樣的方法穿件字段star和time
ID一般設置為int 長度視情況而定
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python常見數據庫操作技巧匯總》、《Python數學運算技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Keras構建神經網絡踩坑(解決model.predict預測值全為0.0的問題)
這篇文章主要介紹了Keras構建神經網絡踩坑(解決model.predict預測值全為0.0的問題),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07

