前言

爬取网易云的过程中发现每次测试数据都需要把整个程序从头运行一次,效率太低,于是就想到了直接把爬取的数据存到数据库里一劳永逸。

贴一篇基础教程(131条消息) python之sqlite3使用详解_hunyxv的博客-CSDN博客_python sqlite3

建立数据库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1,建表:
cu.execute('create table catalog (id integer primary key,pid integer,name varchar(10) UNIQUE)') 上面语句创建了一个叫catalog的表,它有一个主键id,一个pid,和一个name,name是不可以重复的。

2,插入数据:
cu.execute("insert into catalog values(0, 0, 'name1')") cu.execute("insert into catalog values(1, 0, 'hello')") 简单的插入两行数据,不过需要提醒的是,只有提交了之后,才能生效.我们使用数据库连接对象cx来进行提交commit和回滚rollback操作.
cx.commit()

3,查询:
cu.execute("select * from catalog") 要提取查询到的数据,使用游标的fetch***函数,如:
print cu.fetchall() 返回结果如下:
[(0, 0, u'name1'), (1, 0, u'hello')] 如果我们使用cu.fetchone(),则首先返回列表中的第一项,再次使用,则返回第二项,依次下去.

4,修改:
cu.execute("update catalog set name='name2' where id = 0")

cx.commit() 注意,修改数据以后提交

5,删除:
cu.execute("delete from catalog where id = 1") cx.commit() 以上简单的操作反应的Python SQLITE数据库操作的基本要点,这里点到为止.然后,SQLite的强大,并不仅限于此,其对SQL高级特性的支持及其小巧灵活的特点,使得SQLite在众多领域受到开发者的青睐.

思路与实践

目前想不出啥高级用法于是只简单建立数据库并进行查询。。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def init_database(path):					#初始化数据库
conn = sqlite3.connect(path)
c = conn.cursor()
sql = '''
create table music(
name text,
sname text,
link text,
sID text
)
'''
c.execute(sql)
conn.commit()
conn.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def Savedata2(path):			#将排行榜数据存入数据库里
init_database(path)
conn = sqlite3.connect(path)
cur = conn.cursor()
for i in range(len(Sing)):
item = Sing[i]
index = Singer[i]
dd = '''
insert into music(
name,link,sname,sID
)
values("%s","%s","%s","%s")
''' % (item[0],item[1],index[0],index[1])
cur.execute(dd)
conn.commit()
conn.close()
print("OVER")

做完之后发现爬取到的数据里面还有歌手ID这东西没啥用,闲着也是闲着,就想再做一个功能:通过查询歌手爬取该歌手的所有歌曲。主要是从数据库里查询歌手的ID

1
2
3
4
5
6
7
8
9
10
11
12
13
def pdatabase(path,name):			#数据库路径,歌手姓名
con = sqlite3.connect(path)
cur = con.cursor()
sql = '''
SELECT sID FROM music
WHERE sname = "%s"
''' % (name)
cur.execute(sql)
data = cur.fetchall()
slink = 'https://music.163.com/#' + str(data[0]).strip("(").strip(")").strip(",").strip("'")
Getdata(slink)
cur.close()
con.close()

经过简单加工,得到以下代码

查看源码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from bs4 import BeautifulSoup
import re
import sqlite3 #进行SQlite数据库操作
from selenium import webdriver
from selenium.webdriver.chrome.service import Service


def Askurl(url):
s = Service(r"E:\python\PyCharm Community Edition 2021.3.1\plugins\python-ce\helpers\typeshed\stubs\selenium\selenium\webdriver\chrome\chromedriver.exe")
driver = webdriver.Chrome(service=s)
driver.get(url)
driver.switch_to.frame("g_iframe")
text = driver.page_source
return text

Sing = []

def Getdata(url):
FindName = re.compile(r'<b title="(.*?)">')
FindId = re.compile(r'<a href="(.*?)">')

html = Askurl(url)
soup = BeautifulSoup(html,"html.parser")

for item in soup.find_all('div', class_="ttc"):
item = str(item)
data = []
name = re.findall(FindName, item)[0]
name = name.replace('\xa0'," ")
data.append(name)

Id = re.findall(FindId, item)
surl ='http://music.163.com/song/media/outer/url?id=' + str(Id).strip('[').strip(']').strip("'").strip('/song?id=') + '.mp3'
data.append(surl)

Sing.append(data)
for item in Sing:
print(item)

def pdatabase(path,name):
con = sqlite3.connect(path)
cur = con.cursor()
sql = '''
SELECT sID FROM music
WHERE sname = "%s"
''' % (name)
cur.execute(sql)
data = cur.fetchall()
slink = 'https://music.163.com/#' + str(data[0]).strip("(").strip(")").strip(",").strip("'")
Getdata(slink)
cur.close()
con.close()
def main():
path = 'music.db'
pdatabase(path,input())

if __name__ == "__main__":
main()

运行结果: