1.數(shù)據(jù)采集邏輯
在進(jìn)行數(shù)據(jù)采集之前,明確哪些數(shù)據(jù)為所需,制定數(shù)據(jù)Schema為爬取工作做出要求,并根據(jù)數(shù)據(jù)Schema制定出有針對性的爬取方案和采集邏輯。

2.數(shù)據(jù)Schema

3.數(shù)據(jù)爬取
抓取平臺任一商品的評論信息,此案例抓取的商品是某一店鋪的車?yán)遄釉u價信息。
評論信息是由JS動態(tài)加載的,所以直接抓取商品詳情頁的URL并不能獲得商品評論信息。因此我們需要先找到存放商品評價信息的文件,通過使用瀏覽器的開發(fā)者工具進(jìn)行查找。
目標(biāo)URL地址:

通過發(fā)現(xiàn)可知,productId為當(dāng)前商品的商品Id,page為頁碼(從0開始),爬取該商品的所有評價信息只需要改變page參數(shù)即可。(商品評價頁只顯示前100頁,所以page最大值為99)
導(dǎo)入庫
import random
import requests
import json
import re
import csv
import time
import pymysql
對爬蟲程序進(jìn)行偽裝
header = {
'refer': 'https: // item.jd.com /',
'cookie': '',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50'
}
抓取商品評論信息
將python程序偽裝成瀏覽器后,就可以對評論信息進(jìn)行爬取,在前面的分析中,productId和page為重要參數(shù),在本案例中爬取的商品為車?yán)遄樱琾roductId已確定,只需要對page進(jìn)行更改即可達(dá)到需要。通過parms提交參數(shù),使代碼更有邏輯感并方便更改兩個重要參數(shù)。

4.防止反爬,每爬取一頁數(shù)據(jù)后,設(shè)置程序休眠環(huán)節(jié)
# 程序休眠
time.sleep(random.randint(40, 80) * 0.1)
print('第%d頁正在爬取' % (page + 1))
爬取完成后,需要對頁面進(jìn)行編碼,不影響后期的數(shù)據(jù)提取和數(shù)據(jù)清洗工作。
使用正則對數(shù)據(jù)進(jìn)行提取,返回字符串。
字符串轉(zhuǎn)換為json格式數(shù)據(jù)。
res.encoding = 'gb18030'
html = res.text
data = re.findall('fetchJSON_comment98\((.*?)\);', html)
data = json.loads(data[0]) # 將處理的數(shù)據(jù)進(jìn)行解析
comments = data['comments']
print(data['comments'])
4.數(shù)據(jù)存儲
存儲到csv文章來源:http://www.zghlxwxcb.cn/news/detail-505887.html
# 寫入csv文件
f = open("evalution_data.csv", "a", newline='', encoding='gb18030')
header = ["id", "content", "creationTime", "score", "productColor", "productSize"]
# 創(chuàng)建一個DictWriter對象,第二個參數(shù)就是上面創(chuàng)建的表頭
writer = csv.DictWriter(f, header)
writer.writeheader()
for i in comments:
id = i['id']
content = i['content']
creationTime = i['creationTime']
score = i['score']
productColor = i['productColor']
productSize = i['productSize']
writer.writerow(
{"id": id, "content": content, "creationTime": creationTime, "score": score, "productColor": productColor,
"productSize": productSize})
f.close()
存儲到數(shù)據(jù)庫文章來源地址http://www.zghlxwxcb.cn/news/detail-505887.html
# 寫入數(shù)據(jù)庫
conn = pymysql.connect(host='', user='', password='', port=, db='')
cursor = conn.cursor()
for i in comments:
id = i['id']
content = i['content']
creationTime = i['creationTime']
score = i['score']
productColor = i['productColor']
productSize = i['productSize']
sql = "insert into evalution_data(id,content,creationTime,score,productColor,productSize) values('%d','%s','%s','%d','%s','%s')"
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()
到了這里,關(guān)于Python爬取商品評價-京東的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!