1. 程式人生 > 程式設計 >Python資料持久化儲存實現方法分析

Python資料持久化儲存實現方法分析

本文例項講述了Python資料持久化儲存實現方法。分享給大家供大家參考,具體如下:

1、pymongo的使用

前三步為建立物件

  • 第一步建立連線物件
conn = pymongo.MongoClient('IP地址',27017)
  • 第二步建立庫
db = conn['庫名']
  • 第三步建立表
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)
    #建立庫物件
    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("執行時間%.2f" % (end - begin)) #注不完美,仍然需修改

2、mysql的使用

Mysql-front視覺化工具,建庫建表新增欄位

1、建立連線物件:db = pymysql.connet

2、建立遊標物件:cursor = db.sursor

3、執行命令:cursor.execute()

4、提交到資料庫執行

5、關閉:cursor.close

mysql-Front使用流程

1、建立資料庫:

localhost--資料庫--新建---資料庫

資料庫名改為maoyan (專案mysql庫名)--- 字符集utf8 ---確定

2、建立表:

流程:選中maoyao資料庫 --選中資料 ----新建 ----出現新增選單 ---名稱改為top100 ---建立成功

3、往表格中新增欄位:

流程:選中top100表單 --- 資料庫 ----新建 ----欄位 ---出現新增介面 ----名稱改為name ---預設varchar ---- 長度50 --確定

用同樣的方法穿件欄位star和time

ID一般設定為int 長度視情況而定

更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python常見資料庫操作技巧彙總》、《Python數學運算技巧總結》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧彙總》

希望本文所述對大家Python程式設計有所幫助。