python(数据分析与可视化)五
爬虫与数据库连接
1.sqlite数据库
#持久化:把内存中爬取的数据持久的存储到硬盘上面,供以后使用
#方案一:csv,excel 方案二:数据库
#数据库:关系型 sqlite microsoftAccess Mysql/SQLServer/PostgreSQL(django odoo)/ORACLE
#非关系型: nosql not only sql, mongodb/redis
#sqlite非常轻量级,字段类型少,不需要安装,默认没有用户名密码,在手机app中大量应用
#驱动: python -> 驱动 -> 数据库操作底层接口
下面是一个简单的举例:
import sqlite3
# 连接数据库服务,如果不存在会自动生成
connect = sqlite3.connect('./testsqlite.db')
#从会话连接生成游标,相当于excel中的光标,光标定位到一行一个格子,才能开始数据操作
cursor = connect.cursor()
#execute(sql) #ctrl+shift+u 大小写转换
cursor.execute("""
CREATE TABLE if not exists student (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
);
""")
# 插入一条测试数据
cursor.execute("""
insert into student (name,age) values('小明',14);
""")
#插入带参数的数据
name = '小李'
age = 23
# 注意name变量拼到sql字符串中,字符串变量外层补引号
# insert_sql = f"""
# insert into student (name,age) values('{name}',{age});
# """
# print(insert_sql)
#推荐使用execute方法自带的?占位符,然后传入相同个数的参数
cursor.execute("""insert into student (name,age) values(?,?);""",[name,age])
#提交确认(插入和更新需要)
connect.commit()
#查询
cursor.execute("""
select * from student;
""")
rs = cursor.fetchall()
print(rs)
#先关闭游标
cursor.close()
#再关闭数据库
connect.close()
2.数据库图形化工具
3.京东爬虫数据库版
为了尽可能说明情况,下面我以代码的形式来简单讲解一下爬虫与数据库的连接
import json
import requests
import sqlite3
import time
def get_one_product_one_page_comments(pid,pageno=1):
"""
取一个商品的一页评论
:param pid: 商品id
:param pageno: 评论第几页
:return: [{}]
"""
base_url = 'https://club.jd.com/comment/productPageComments.action'
#本次请求头只用伪造users-agent即可,但前段时间测试需要cookie字段
headers = {
# 'Cookie': '__jdv=76161171|direct|-|none|-|1610928737206; __jdu=1610928737155940443424;',
# 'Referer': 'https://item.jd.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'
}
#tips:从开发者工具network请求头下面的query params复制下来再调整,使用编辑器列编辑模式 alt+shif+鼠标拖动
params = {
#'callback': 'fetchJSON_comment98', #特殊的 jsonp->json
'productId': pid, #商品id
'score': 0,
'sortType': 5,
'page': pageno, #第几页
'pageSize': 10,
'isShadowSku': 0,
'rid': 0,
'fold': 1
}
# for i in range(1,11):
# params['page'] = i
resp = requests.get(base_url,headers=headers,params=params)
status_code = resp.status_code
comments_json = resp.text
#print(comments_json)
#京东评论接口返回得到的是jsonp 格式,涉及跨域问题,需要先将jsonp转为json
#方法一:python字符串方法删除固定长度无用字符串
#方法二:(推荐)上网找从jsonp过滤json正则
#方法三:本例中发现修改参数可以直接访问json
comments_obj = json.loads(comments_json)
#print(comments_json)
comments = comments_obj['comments']
return comments
def write_comment_to_db(c,cursor):
cid = c['id']
content = c['content']
# images = c.get('images',None)
creation_time = c['creationTime']
product_color = c['productColor']
#
# cursor.execute("""select * from jingdong where cid=?""",cid)
# if not cursor.fetchone:
# [(cid,'内容','颜色'),()]
# 一条评论写入数据库
cursor.execute("""insert into comm (cid,content,creation_time,product_color) values(?,?,?,?);""",
[cid, content, creation_time, product_color])
if __name__ == '__main__':
#数据库初始化
connect = sqlite3.connect('./jd.db')
cursor = connect.cursor()
# execute(sql) #ctrl+shift+u 大小写转换
cursor.execute("""
CREATE TABLE if not exists comm (
id INTEGER Primary key,
cid integer,
content TEXT,
creation_time data,
product_color text
);
""")
product_id = 100009077475
for pageno in range(1,100):
one_page_comments = get_one_product_one_page_comments(pid=product_id,pageno=pageno)
for c in one_page_comments:
write_comment_to_db(c,cursor)
connect.commit()
print(f'第{pageno}页插入完成')
time.sleep(1) #防止被封号
connect.close()
4.jieba分词
#后续需求:分析评论的感情色彩,人们对商品喜欢还是厌恶。这种需求不同于统计颜色百分比,价格高低这种数学能直接#想个办法:先把句子,分成词汇,看词汇感情色彩,从局部词汇推断整体。
#第一个问题;如何把句子分成词汇。
#’本来打算等等国产新机发售.我到郑州大学游玩了一圈′―分成词汇〔‘来’,‘打算’,‘国产’,‘发售’,"’,J
#有人已经利用AI、数学相关算法实现了分词库,我们可以直接调用。
#jieba分词库:目前最流行的分词库,github https:/ /qithub.com/fxsjuy/jieba#pip install jieba
下面是一个简单的举例:
import jieba
long_str = '把一句话,按照词汇分离,加油奥里给'
words = jieba.cut(long_str,cut_all=False)
#print(words) #得到<generator object Tokenizer.cut at 0x0000026BA92F9840>
print('/'.join(words))
#生成器 range() ,生成序列、生成列表的制造者,生成的序列可以被循环
#generator.__next__() 生成器的方法,东西非常多,每次生产一个,速度快且节省空间,生成器只能迭代一次
# -------------------
import sqlite3
import jieba
connect = sqlite3.connect('./jd.db')
cursor = connect.cursor()
cursor.execute("""select * from comm order by creation_time desc limit 0,100;""")
comments_rs = cursor.fetchall() #[(cid,connect,product_color),()]
#comments = []
# for c in comments_rs:
# connect = c[2]
# comments.append(connect)
# print(comments)
comments = [c[2] for c in comments_rs]
comments = ''.join(comments) #把所有评论拼成一个长字符串
words = jieba.cut(comments,cut_all=False)
print('/'.join(words))
#print(w for w in words)
5.停止词
#如果上一节分词后的词汇结果,做词频统计,会发现‘的’、‘,’、‘。’等出现的次数过多,影响了最终的分析结果
#所以需要把数据里的无用杂质剔除出来
#stop words:有人专门整理好的无用词汇
comment_word_list = ['评估','但是','1','打算','暗藏','从',',']
with open('./dict/stop_words_zh.txt',mode='r',encoding='utf-8') as f:
# stop_words = f.readlines()
# stop_words = [stop_words.strip() for stop_words in stop_words]
stop_words = f.read()
#print(stop_words)
filterd_comment_word_list = []
for word in comment_word_list:
if word not in stop_words:
filterd_comment_word_list.append(word)
print(filterd_comment_word_list)
今天的分享就到这里,如果还想了解更多,可以看我主页!