Python爬虫 获得淘宝商品评论

自从写了第一个sina爬虫,便一发不可收拾。进入淘宝评论爬虫正题:


  在做这个的时候,也没有深思到底爬取商品评论有什么用,后来,爬下来了数据。觉得这些数据可以用于帮助分析商品的评论,从而为用户选择商品提供一定的可参考数据。

  找评论所在真实url:有了前面爬搜狗图片的经验,面对找资料的url这件事,找他的速度是比第一次快了不少。首先进宝贝页面,如图

发现评论与搜狗图片类似,均为动态刷新。因此,F12(开发者选项)>>Notework>>F5(刷新)>>feedRateList(文件名)>>Headers>>复制Request URL  

  去除不必要的字段,获得需要的资料(评论)所在url= https://rate.taobao.com/feedRateList.htm?auctionNumId=39595400262&currentPageNum=1

猜测url地址为商品id,PageNum为评论的所在页数。因此要把所有页的评论遍历一遍。则应取Num的值递增访问,统计评论,直至输出的评论数等于总评为止,Num不再叠加,当然叠加后肯定是404喽。

愉快的代码时间:

import requests
import json
def getCommodityComments(url):
    if url[url.find('id=')+14] != '&':
        id = url[url.find('id=')+3:url.find('id=')+15]
    else:
        id = url[url.find('id=')+3:url.find('id=')+14]
    url = 'https://rate.taobao.com/feedRateList.htm?auctionNumId='+id+'&currentPageNum=1'
    res = requests.get(url)
    jc = json.loads(res.text.strip().strip('()'))
    max = jc['total']
    users = []
    comments = []
    count = 0
    page = 1
    print('该商品共有评论'+str(max)+'条,具体如下: loading...')
    while count<max:
        res = requests.get(url[:-1]+str(page))
        page = page + 1
        jc = json.loads(res.text.strip().strip('()'))
        jc = jc['comments']
        for j in jc:
            users.append(j['user']['nick'])
            comments.append( j['content'])
            print(count+1,'>>',users[count],'\n        ',comments[count])
            count = count + 1

getCommodityComments('https://item.taobao.com/item.htm?id=39595400262&')

来来来,看一下效果:

综上,Python爬虫的关键就在于获取所要爬取资料所在真实url,得到该url后,只需要做相应处理,for循环遍历所有页即可爬取获得资料,重要的资料亦可写进数据库。

猜你喜欢

转载自blog.csdn.net/IAlexanderI/article/details/81133698