直接送上代碼
import urllib.request
import json
import jsonpath
import time
end_page = int(input('請輸入爬取的結束頁碼:'))
for i in range(0,end_page+1):
print('第%s頁開始爬取------'%(i+1))
url = 'https://sclub.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98vv385&productId=52322470877&score=0&sortType=5&page={}&pageSize=10&isShadowSku=0&fold=1 '
'https://sclub.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98vv319&productId=10421264905&score=0&sortType=5&page=0&pageSize=10&isShadowSku=0&fold=1'
url = url.format(i)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
'Referer': 'https://item.jd.com/52322470877.html'
}
request = urllib.request.Request(url=url,headers=headers)
content = urllib.request.urlopen(request).read().decode('gbk')
content = content.strip('fetchJSON_comment98vv385();')
obj = json.loads(content)
comments = obj['comments']
fp = open('京東.txt','a',encoding='utf8')
for comment in comments:
#評論時間
creationTime = comment['creationTime']
#評論人
nickname = comment['nickname']
#評論內容
contents = comment['content']
#評論圖片
if 'images' in comment:
img_src = jsonpath.jsonpath(comment,'$..images[*].imgUrl')
img_src = 'https:' + str(img_src).strip('[]')
else:
img_src = '無圖片'
item = {
'評論時間': creationTime,
'用戶': nickname,
'評論內容': contents,
'圖片地址': img_src,
}
string = str(item)
fp.write(string + '\n')
print('第%s頁完成----------'%(i+1))
time.sleep(4)
fp.close()
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
