目錄
閒言
這幾天忙的要老命啊,天天上網課,5,6個平臺手機電腦電視全開,一整天盯着顯示屏,我覺得遲早要崩潰,不僅如此,在學校上課基本沒什麼作業,一上網課就:你的作業即將過期,請及時完成。。。好了,吐槽不說了,忙中抽點閒,前兩天弄的東西現在寫一寫,雖然網上有一堆大神有寫這個東西,但是我喜歡折騰,就把我自己踩的坑來寫一寫。
成果
小聲嘀咕:形狀是雷大佬的圖片。๑乛◡乛๑
填坑
一開始我是想着直接獲取網頁試試,不出意外啥都沒有,不過也很好理解,畢竟大網不可能用這麼簡單的鼠標右鍵查看網頁源代碼就能看到,其實我們平時直接requests獲取到的網頁就是跟鼠標右鍵查看網頁源代碼看到的一樣,所以以後如果做這種事我們就可以先了解一下網站構成,也就是鼠標右鍵查看網頁源代碼,不然有時候真的瞎忙活。
接着呢我又嘗試了selenium動態獲取,成是成功了,只不過每頁獲取到的只是一個評論,也許是我的方法錯了,代碼就不貼了,太拙劣了。我在這差不多耗了整整一個小時的時間,那會真的頭都大了,不過我還是發現了火狐的F12的一個好用處,竟然可以直接獲取到Xpath路徑,直接點擊標籤然後鼠標右鍵copy就有個copy Xpath還有其他一些方法,可能是我太蠢了吧現在才發現,不過好像不太晚,哈哈哈哈哈。
最後沒辦法去找了一下,發現還真是自己太蠢了,其實網上已經有一堆了,受該作者的啓發我又把之前的源碼全部刪去(心疼),然後又折騰了一下午搞了下面這份,源碼已經有很好的註釋了,就不再去寫思路了,終於完結了!!*★,°*:.☆\( ̄▽ ̄)/$:*.°★*。撒花!
網址詳解
https://sclub.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98&productId=100011199522&score=1&sortType=6&page=0&pageSize=10&isShadowSku=0&fold=1
返回模式:callback 商品id:productId=100011199522
評論方式:score=0全部 1差評 2中評 3好評 5追評
排序方式:sortType=5 推薦排序 6時間排序
頁面:page=0
一頁多少評論:pageSize=10
未知:isShadowSku=0
未知:fold=1
代碼
數據庫:data_sql.py
# -*- coding:utf-8 -*-
import sqlite3
#創建數據庫
def thing_opendb():
conn = sqlite3.connect("JD_date.db")
cur = conn.execute("""create table if not exists comments_info(productName varchar(126),commentTime char(30),content varchar(512))""")
return cur,conn
# 往數據庫中添加內容
def thing_insertData(productName,commentTime,content):
hel = thing_opendb()
hel[1].execute("insert into comments_info(productName,commentTime,content)values (?,?,?)",(productName,commentTime,content))
hel[1].commit()
hel[1].close()
# 刪除數據庫中的全部內容
def thing_delalldb():
hel = thing_opendb() # 返回遊標conn
hel[1].execute("delete from comments_info")
print("刪庫跑路Cxk我最帥")
hel[1].commit()
hel[1].close()
#查詢全部內容
def thing_slectTable():
hel = thing_opendb()
cur = hel[1].cursor()
cur.execute("select * from comments_info")
res = cur.fetchall()
#for line in res:
#for h in line:
#print(h),
#print(line)
return res
cur.close()
#查詢全部評論信息
def thing_slectComment():
hel = thing_opendb()
cur = hel[1].cursor()
cur.execute("select content from comments_info")
res = cur.fetchall()
#for line in res:
#for h in line:
#print(h),
#print(line)
return res
cur.close()
源碼
import requests
import re
import time
import json
#數據庫
from date_sql import *
#詞雲庫
from wordcloud import WordCloud
import PIL .Image as image
import numpy as np
def get_comment(url):
r = requests.get(url).content
text=r.decode('gbk')
#獲取返回的json數據
# print(text)
data=text
#返回的並不是字典,我們要先處理一下,把無用字符去除,留下字典
data1=data.replace("fetchJSON_comment98(", "");
data2=data1.replace(");", "");
# print(data2)
data = json.loads(data2)#data1的內容爲一個字典,用{}括起來的內容
#字典清洗,提取comments內容
for i in data['comments']:
#商品名稱
productName = i['referenceName']
#評論時間
commentTime = i['creationTime']
#評論內容
content = i['content']
#將數據插入數據庫保存
thing_insertData(productName,commentTime,content)
print('ok')
#我爬取的時候總共0-35頁每頁10條數據 36頁還有2條就不要了
#分批獲取,防止封本人是0,11---11,21---21,35
for i in range(21,35):
number=str(i)
url = "https://sclub.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98&productId=100011199522&score=1&sortType=6&page=%s&pageSize=10&isShadowSku=0&fold=1"%number
get_comment(url)
#防止封,加定時,每隔1秒獲取一頁
time.sleep(1)
print('爬取完成')
# 查詢總共幾條數據
a=thing_slectTable()
print(len(a))
# print(a)
#從數據庫獲取全部評論
b=thing_slectComment()
print(len(b))
# print(b)
#將數據寫入txt文件
file = open('jingdongComments.txt','w')
for i in b:
#暴力去掉無用字符寫入txt文件
strs=str(i)[2:][:-2].replace("\n", "")
strs=strs.replace("…", "")
strs=strs.replace("rdquo", "")
strs=strs.replace("ldquo", "")
strs=strs.replace("運行速度", "")
strs=strs.replace("拍照效果", "")
strs=strs.replace("待機時間", "")
strs=strs.replace("外形外觀", "")
strs=strs.replace("其他特色", "")
strs=strs.replace("屏幕音效", "")
strs=strs.replace("n", "")
file.write(strs)
file.close()
print('寫入ok')
#讀取txt文件
with open("jingdongComments.txt") as fp:
text=fp.read()
# 將文本放入WordCoud容器對象中並分析
# 詞雲圖片
mask = np.array(image.open("2.jpg"))
#字體:C:\Windows\Fonts\FZSTK.TTF C:\Windows\Fonts\FZLTCXHJW.TTF 每個人的系統字符庫裏都有
font="C:\Windows\Fonts\FZLTCXHJW.TTF"
WordCloud =WordCloud(
# 設置字體,不指定就會出現亂碼
font_path=font, # 這個路徑是pc中的字體路徑
# 設置背景色
background_color='white',
# 詞雲形狀
mask=mask,
# 允許最大詞彙
max_words=100,
# 最大號字體
max_font_size=100,
# 設置有多少種隨機生成狀態,即有多少種配色方案
random_state=30,
# 清晰度
scale=3
).generate(text)
image_produce = WordCloud.to_image()
image_produce.show()
print('詞雲完成')
亂語
學習使用我只爬取了差評,數據量比較少,官網顯示500+,最後爬下來350+,可能有些客服回覆也算評論,那也算挺厚道的了,總評好像4w+,本來打算全弄下來,但發現沒多大用處就不搞了。將商品id換一下不知道能不能獲取到信息了,沒試過,不過我覺得應該也是可以的。