一,爬虫需求分析
1,需求。
我们需要获取多个链接的白酒在2018年评论数量。
2,分析。
一个商品页面有好几个规格,如图:
评论区我们需要获取的数据是当前选择的商品,而且需要时间顺序为2018年的:
这时候得到的评论有很多页,我们需要一条条的去爬取。
二,误区
因为时间排序以及当前商品评论的限制,我们选择了Selenium作为爬虫工具,写了很久发现时间排序的那个地方不是标签,在标签选取上出现了问题,所以放弃了该方法。
三,productPageComments实现
1,选择本方法的原因
我们发现我们需要爬取的链接中都有商品ID,而不同规格的商品ID也不同,如果用productPageComments获得评论的话那么相当于解决了仅获取当前商品评论的问题,现在只需要完成2018评论数量的限制了。
2,实现
通过依此读取链接的方法用for循环页数爬取所有的评论。要是获取的productPageComments中没有评论咋办?只需要让前N页的评论总数与前N-5页对比,若没变化,则说明后面都没有评论了,程序停止。
2018的限定只需要把爬取的日期取前4位,然后用正则匹配2018即可。
1 for i in data['comments']:2 #name = i['referenceName'] #酒的种类
3 time_comment = i['creationTime'][0:4] #只选择评论时间的年份,若为2018开头则符合要求
4 time_comments.append(time_comment)5 total_com_num.append(time_comments.count("2018")) #[每页的评论数],所以得注意所以页码如何处理?
3,总代码
1 importrequests2 importjson3 importre4
5 total_com_num = [] #用于计算总评论数
6 defgetcontent(url):7 productPageComments =requests.get(url)8 data = json.loads(productPageComments.text[26:-2]) #translate to json
9
10 time_comments = [] #本容器用于筛选出时间正确的商品
11 for i in data['comments']:12 #name = i['referenceName'] #酒的种类
13 time_comment = i['creationTime'][0:4] #只选择评论时间的年份,若为2018开头则符合要求
14 time_comments.append(time_comment)15 total_com_num.append(time_comments.count("2018")) #[每页的评论数],所以得注意所以页码如何处理?
16 return sum(total_com_num) #返回前i页(note:这个i是page的i)下评论总数。
17
18 if __name__ == '__main__':19 link_list =[]20 f = open("1.txt") #返回一个文件对象
21 lines = f.readlines() #调用文件的 readline()方法
22 for line inlines:23 link_list.append(line)24
25 #link = "https://item.jd.com/21391048137.html#comment"
26 #goods_id = int(re.findall('\d+', link)[0]) # 装你要找的商品的商品ID,[6873309,第二个商品ID,第三个商品ID。。。] 100000766433
27 page = 500 #页码最大值,如果评论的页码数量大于500则得到的数据会不准确。
28
29 list=[]30 step = 5 #前i与i-5数量一致的话,代码就停止
31
32 for link inlink_list:33 goods_id = int(re.findall('\d+', link)[0]) #装你要找的商品的商品ID,[6873309,第二个商品ID,第三个商品ID。。。] 100000766433
34
35 #括号为商品ID,为了支持翻页
36 for i in range(page): #i from zero to page
37 url = "https://sclub.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98vv4640&productId=" + str(goods_id) + "&score=0&sortType=5&page="+str(i)+"&pageSize=10&isShadowSku=0&rid=0&fold=1"
38 list.append(getcontent(url))39 if (i>step) and (list[i] == list[i-step]):40 #print("第",i,"页停止程序!",goods_id,list[-1])
41 print("第",i,"页停止程序!",list[-1])42 break
四,总结
json和re还不够熟练,有待加强。

1359

被折叠的 条评论
为什么被折叠?



