文章目录
- 京东评论爬取->入库
- 1. sqlite数据库
- 2.数据库图形化工具
- 1).数据库
- 2)datagrip
- 3.京东评论爬取(导入数据库)
- 4.jieba分词
- 1) jjieba分词
- 2) 生成器
- 5.停止词
京东评论爬取->入库
提示:以下是本篇文章正文内容,下面案例可供参考
1. sqlite数据库
- 持久化:把内存中爬取的数据存储到硬盘上,供以后使用。
- 方案1;csv.excel。方案2:数据库。
- 数据库:关系型 sqlite access mysql/SQLServer/PostgresSQL(推荐) (django odoo)/ORACLE
- nosql not only sql, mongodb/redis
- sqlite 非常轻量级,字段类型少,不需安装,默认没有用户名密码,在手机app中大量使用
- sqlite驱动: python ->驱动 -> 数据库操作底层接口
import sqlite3
# 连接数据库服务 ,如果不存在,会自动生成
connect = sqlite3.connect('./textsqlite.db')
# 从会话连接生成游标,相当于光标
cursor = connect.cursor()
# execute(sql)
# name Text, #字符串
# age integer 数字
cursor.execute("""
CREATE TABLE IF NOT EXISTS student(
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
);
""")
# 插入一条测试数据
cursor.execute("""
INSERT INTO student (name,age) VALUES ('小明',13);
""")
# 插入带参数的数据
name = '小红'
age = 16
# '{name}'记得加''
#注意name变量拼到sql字符串中,字符串变量外层补引号。
#insert_sql = f"""INSERT INT0 student (name,ace) VALUES ( 'iname} ' , 〈acel): " "1"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.数据库图形化工具
1).数据库
- oracle plsql
- mysql phpadmin mysql-workbench(体验不错但只支持mysql)
- navicat比较流行,支持多数据库
- datagrip越来越流行,操作跟pycharm一致,界面UI好,支持多数据库
2)datagrip
- 添加数据源
- 第一次下载driver
- 驱动:python -> 驱动 -> 数据库操作底层接口
3.京东评论爬取(导入数据库)
#
import json
import sqlite3
import time
import requests
def get_one_product_one_page_comments(pid, pageno=1):
"""
取一个商品的一页评论
:param pid: 商品id
:param pageno: 评论第n页
:return: [{'content': ''}, {}]
"""
base_url = 'https://club.jd.com/comment/productPageComments.action'
# 本次请求头只用伪造user-agent即可,但前端时间测试需要cookie字段
headers = {
# 'Referer': 'https://item.jd.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',
}
# tips:从开发者工具network请求头下面的query params复制下来再调整。使用编辑器列编辑模式 alt+shift+鼠标拖动。
params = {
#'callback': 'fetchJSON_comment98',
'productId': pid, # 商品id
'score': 0,
'sortType': 5,
'page': pageno, # 第n页 经测试最大99页,之后只有概括数据无详细数据。
'pageSize': 10,
'isShadowSku': 0,
'rid': 0,
'fold': 1
}
# for i in range(1, 20):
# 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。
# 方法1:python字符串方法删除固定长度无用字符串;2(推荐)上网找从jsonp过滤json正则;3本例中发现修改参数可以直接返回json
comments_obj = json.loads(comments_json)
print(comments_obj)
comments = comments_obj['comments']
return comments
def write_comment_to_db(c, cursor):
cid = c['id']
content = c['content']
creation_time = c['creationTime']
images = c.get('images', None)
product_color = c['productColor']
product_Size = c['productSize']
# 为避免重复插入,先判断
# cursor.execute("""select * form comments where cid=?""", [cid])
# if not cursor.fetchone:
# [(cid, '内容', '绿色', '2021-'), ()]
# 一条评论写入数据库
cursor.execute("""
insert into comments (cid, content, product_color, creation_time)
values (?, ?, ?, ?);
""", [cid, content, product_color, creation_time])
#有能力的小伙伴页可将此进行封装,在此我就不进行演示了
# def db_init():
# # 数据库初始化
# connect = sqlite3.connect('./jd.db')
# cursor = connect.cursor()
# cursor.execute("""
# CREATE TABLE IF NOT EXISTS comments (
# id INTEGER PRIMARY KEY,
# cid INTEGER,
# content TEXT,
# product_color TEXT,
# creation_time DATETIME
# );
# """)
if __name__ == '__main__':
connect = sqlite3.connect('./textsqlite.db')
cursor = connect.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY,
cid INTEGER,
content TEXT,
product_color TEXT,
creation_time DATETIME
);
""")
product_id = 100009077475
for pageno in range(1, 10):
one_page_comments = get_one_product_one_page_comments(product_id, pageno)
for c in one_page_comments:
write_comment_to_db(c, cursor)
connect.commit()
print(f'第{pageno}页数据插入完成')
time.sleep(1)
connect.close()
实验结果(是在datagrip中观察到的):
4.jieba分词
1) jjieba分词
- 后续需求;分析评论的感情色彩,人们对商品喜欢还是厌恶。这种需求不同于统计颜色百分比,价格高低这种数学能直#想个办法:先把句子,分成词汇,看词汇感情色彩,从局部词汇推断整体。
- 第一个问题:如何把句子分成词汇。
- ′本来打算等等国产新机发售.我到郑州大学游玩了一圈′―分成词汇〔‘来’,‘打算’,‘国产’,‘发售’,"",J
- 有人已经利用AI、数学相关算法实现了分词库,我们可以直接调用。
- jieba分词库;目前最流行的分词库,github https://qithub.com/fxsju/jieba
- pip install jieba
import jieba
long_str = '把一句话,按照词汇分离,为后面的分析统计做准备'
words = jieba.cut(long_str, cut_all=False)
# print('/'.join(words)) # <generator object Tokenizer.cut at 0x00000252011E7C80>
result = ''
for w in words:
result = result + w + '/'
print(result)
2) 生成器
- 生成器 range(10000),生成列表,序列的制造者,生成的序列可以被循环
- generator .next() 东西非常多,每次生产一个,速度快且节省内存。生成器只能被迭代一次。
import sqlite3
connect = sqlite3.connect('./textsqlite.db ')
cursor = connect.cursor()
cursor.execute("""select * from jd_comments order by creation_time desc limit 0,100;""")
comments_rs = cursor.fetchall() # [(id, cid, content,product_color),()] [{id:3,content: ' )
# comments = []
# for c in comments_rs:
# content = c[3]
# comments.append(content)
# print(comments)
comments = [c[3] for c in comments_rs] # [i*2 for i in list] #比上述循环简单
comments = ''.join(comments) #先拼接成长字符串
words = jieba.cut(comments, cut_all=False)
print('/'.join(words))
5.停止词
- 如果上一节分词后的词汇结果,做词频统计,会发现’的’,’, '。'出现的次数最多,影响了最终的分析结果。
- 所以需要把数据里的无用杂质剔除出来。
- stop words:有人专门整理好了常见无用词汇
- 把上个代码得到的分此后的列表循环,判断每一项是否停止词,是的话删除。
- 要完成此代码需要自己在pycharm中导入网上的"停止词文件"
comment_word_list = ['可能', '它', '还有', '许多', '不足', '8', ',']
with open('./dict/stop_words_zh.txt', mode='r', encoding='utf-8') as f:
stop_words = f.read().splitlines()
# stop_words = [stop_word.strip() for stop_word in stop_words]
# print(stop_words)
filtered_comment_word_list = []
for word in comment_word_list:
if word not in stop_words:
filtered_comment_word_list.append(word)
print(filtered_comment_word_list)