scrapy爬取京東商城某一類商品的資訊和評論(二)
2、任務二:爬取商品評論資訊
如果不需要爬取使用者的地域資訊,那麼用這個網址爬就好:
http://club.jd.com/review/10321370917-1-1-0.html
其中10321370917是商品的ID,評論的第一頁就是 -1-1-0.html, 第二頁就是-1-2-0.html。
之前商品不是存了評論總數嗎,一頁30個評論,除一下就可以知道多少頁了,或者直接抓取下一頁的連結也行。
但是這裡的評論是沒有使用者地區資訊的。下面放兩個圖對比一下
沒地區資訊的:
有地區資訊的:
因此如果不需要地區資訊,就按上面的方法抓取就好,很簡單。但是如果要地區資訊的話,就會複雜一些了。因為你會發現商品詳情頁中的評論也是動態載入的,不管你點第一頁,網址都不變。
老套路,從評論第一頁點到第二頁看network,看都載入了什麼檔案,找出有評論資訊的檔案。
這個比起前面的就少太多東西了。而且只有一個script檔案,不用找,就是它了,點開看看。
很多東西,用線上json解析網站解析一下,對比一下詳情頁的評論發現可以對應上。接下來看看網址:
http://sclub.jd.com/productpage/p-10321370917-s-0-t-3-p-1.html?callback=fetchJSON_comment98vv341
10321370917 是商品ID,第一頁是s-0-t-3-p-1 第二頁是s-0-t-3-p-2 第三頁是s-0-t-3-p-3 這個規律試一試就知道了
fetchJSON_comment98vv341去不掉,而且修改341網頁也會變。這時候我們需要去找找這個341在哪。
點開詳情頁的原始碼,ctrl+F搜尋一下341,發現有一個叫commentVersion的東西,所以在抓取詳情頁的時候需要存一下commentVersion後面的值,在這裡會用到。
看到上一篇抓取商品資訊博文的就知道,之前有個鋪墊。
這部分程式碼:
def parse(self, response): temp1 = response.body.split('productAttr') # if len(temp1) < 2: # item2 = commentItem() # item2['content'] = response.url.encode('utf-8') # return item2 # str = '{"productAttr' + temp1[1][:-2] str = str.decode("gbk").encode("utf-8") js = json.loads(unicode(str, "utf-8")) comments = js['comments'] # 該頁所有評論 items = [] for comment in comments: item1 = commentItem() item1['user_name'] = comment['nickname'] item1['user_ID'] = comment['id'] item1['userProvince'] = comment['userProvince'] item1['content'] = comment['content'] item1['good_ID'] = comment['referenceId'] item1['good_name'] = comment['referenceName'] item1['date'] = comment['referenceTime'] item1['replyCount'] = comment['replyCount'] item1['score'] = comment['score'] item1['status'] = comment['status'] title = "" if comment.has_key('title'): item1['title'] = comment['title'] item1['title'] = title item1['userRegisterTime'] = comment['userRegisterTime'] item1['productColor'] = comment['productColor'] item1['productSize'] = comment['productSize'] item1['userLevelName'] = comment['userLevelName'] item1['isMobile'] = comment['isMobile'] item1['days'] = comment['days'] tags = "" if comment.has_key('commentTags'): for i in comment['commentTags']: tags = tags + i['name'] + " " item1['commentTags'] = tags items.append(item1) return items
全部程式碼已上傳github:
https://github.com/xiaoquantou/jd_spider