Python爬虫 #015 SQLite数据库

爬虫爬取的数据常常储存在TXT文本文件,Excel表格文件,数据库中。Python中常用的数据库有MySQL,MongoDB,SQLite

1. SQLite简介

SQLite是一个轻量级的数据库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。一个数据库就是一个文件



2. Python使用SQLite

  • Python 2.5.x 以上版本默认自带了sqlite3库,不需要 pip install

2.1 创建数据库,并添加内容

import sqlite3

# 已存在则打开,不存在则创建数据库,当前路径test.db文件
conn = sqlite3.connect("test.db")
# 获取游标
cur = conn.cursor()

# 建表语句,表的名称为company,栏目id.......salary
sql = '''
    create table company
        (id int primary key not null,
        name text not null,
        age int not null,
        address char(50),
        salary real);
'''
# 执行sql语句
cur.execute(sql)
# 提交数据给数据库
conn.commit()
# 关闭数据库
conn.close()

此时在当前路径生成了一个数据库文件


2.2 pycharm查看数据库

  • 根据图示操作,在pycharm中能查看数据库内容

  • 第一次使用SQLIte,要下驱动文件,点击Download

  • 选择db文件路径,选择db文件,确定即可

  • 在这就能看到所创建的表



3. SQLite数据库的基本操作

3.1 建表

import sqlite3

# 已存在则打开,不存在则创建数据库
conn = sqlite3.connect("test.db")
# 获取游标
cur = conn.cursor()

# 建表语句,表的名称为company,栏目id.......salary
sql = '''
    create table company
        (id int primary key not null,
        name text not null,
        age int not null,
        address char(50),
        salary real);
'''
# 执行sql语句
cur.execute(sql)
# 提交数据给数据库
conn.commit()
# 关闭数据库
conn.close()

3.2 增

import sqlite3

# 已存在则打开,不存在则创建数据库
conn = sqlite3.connect("test.db")
# 获取游标
cur = conn.cursor()

id = 1
name = "张三"
age = 32
address = "成都"
salary = 8000
data = (id, name, age, address ,salary)

# 插入数据(数据得封装成元组)
sql1 = '''
    insert into company (id, name, age, address ,salary)
     values(?,?,?,?,?)
'''

# 执行sql语句
cur.execute(sql1,data)
# 提交数据给数据库
conn.commit()
# 关闭数据库
conn.close()

若数据被封装成列表,插入数据有两种方法:

# 方法一:把列表转化为元组
data = [1, "张三", 18, "成都", 8000]
tuple_data = tuple(data)
sql1 = '''
    insert into company (id, name, age, address ,salary)
     values(?,?,?,?,?)
'''
# 执行sql语句
cur.execute(sql1,tuple_data)
# 方法二:通过列表索引插入
## 注意 %s 是带引号的,不然会报错
data = [1, "张三", 18, "成都", 8000]
sql = '''insert into company (id, name, age, address ,salary)
         values ("%s", "%s", "%s", "%s", "%s")'''%(data[0], data[1], data[2], data[3], data[4])
# 执行sql语句
cur.execute(sql)

3.3 删

import sqlite3

conn = sqlite3.connect('test.db')
cur = conn.cursor()

# delete from + 表名 + where + 条件
sql = 'delete from company where id=?'
id = (3,)

cur.execute(sql,id)
conn.commit()
conn.close()

3.4 改

import sqlite3

conn =sqlite3.connect('test.db')
cur = conn.cursor()

# update + 表名 + set + 要改的数据 + where + 查找该行数据的条件
sql = 'update company set name=?,address=? where id=1'
data = ('麻子','天堂')

cur.execute(sql,data)
conn.commit()
conn.close()

3.5 查

import sqlite3

# 已存在则打开,不存在则创建数据库
conn = sqlite3.connect("test.db")
# 获取游标
cur = conn.cursor()

# 查询数据(test.db是数据库文件,company是表的名称)
sql = '''
     select id, name, age, address ,salary from company 
'''
# sql = 'select * from company '

# 执行sql语句,执行查询语句获得返回值
result = cur.execute(sql)

for row in result:
    # row表示行,row[0]表示第一列
    # print(row)
    print("id = ", row[0])
    print("name = ", row[1])
    print("age = ", row[2])
    print("address = ", row[3])
    print("salary = ", row[4], '\n')

# 关闭数据库
conn.close()


4. SQLite可视化工具

4.1 安装


4.2 使用

  • 建数据库和表

  • 查询数据库

  • 添加数据



5. 实战案例


5.1 案例一:豆瓣电影数据

import sqlite3
import requests
from lxml import etree
import time

# 建表
conn = sqlite3.connect("movie.db")
cur = conn.cursor()
sql1 = '''
    create table movie_top250
    (
    rank integer primary key autoincrement,
    href text not null,
    ch_title text not null,
    en_title text not null,
    grade text not null,
    evaluate text not null,
    line text not null,
    message text not null
    )
'''
cur.execute(sql1)

a = 0
fp = open(r'D:\movies.txt',mode='a',encoding='utf-8')
for i in range(10):
    url = 'https://movie.douban.com/top250?start=' + str(a) +'&filter='
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3730.400 QQBrowser/10.5.3805.400'
    }
    response = requests.get(url, headers = headers)
    data = response.text

    html = etree.HTML(data)
    movies = html.xpath('//*[@id="content"]/div/div[1]/ol/li')
    # print(len(movies))

    for movie in movies:
        # 有的标题只有中文名
        ## 标题
        titles = movie.xpath('./div/div[2]/div[1]/a/span[@class="title"]')
        if len(titles) == 2:
            ch_title = titles[0].text
            en_title = titles[1].text.replace('/', '')
        else:
            # 没有中文名,英文名设为None
            ch_title = titles[0].text
            en_title = "无"
        # 排名
        rank = movie.xpath('.//em')[0].text
        # 评分
        grade = movie.xpath('.//span[@class="rating_num"]')[0].text
        # 评价人数
        evaluate = movie.xpath('.//div[@class="star"]/span[4]')[0].text
        # 链接
        href = movie.xpath('.//div[@class="hd"]/a/@href')[0]
        # 一句话简介(有的没简介)
        try:
            line = movie.xpath('.//span[@class="inq"]')[0].text
        except:
            line = "无"
        # 电影信息
        message = movie.xpath('.//div[@class="bd"]/p')[0].text.strip()
        data = (rank, href, ch_title, en_title, grade, evaluate, line, message)
        print(data)
        sql2 = '''
            insert into movie_top250 (rank,href,ch_title,en_title,grade,evaluate,line,message)     
            values(?,?,?,?,?,?,?,?)'''
        cur.execute(sql2,data)
        conn.commit()
    a += 25
    time.sleep(2)
fp.close()
cur.close()
conn.close()

查询数据库数据

import sqlite3

# 连接
conn = sqlite3.connect("movie.db")
# 获取游标
cur = conn.cursor()

sql = 'select * from movie_top250'
# sql = '''
#     select rank,href,ch_title,en_title,grade,evaluate,line,message from movie_top250
# '''

result = cur.execute(sql)
for row in result:
    # row 为一行,row[0]为第一行第一列
    print(row)
    # print(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7] + '\n')

posted @ 2023-06-28 23:01  枫_Null  阅读(58)  评论(0)    收藏  举报