您的位置:首页 > 编程语言 > Python开发

python爬虫之三 —— 淘宝评论

2019-01-02 15:49 429 查看

前言

最近看网上的分享文章中,关于淘宝网站,不少朋友都是获取的商品列表数据,我个人其实对顾客的评论也是比较感兴趣的,所以写了一个简单的爬虫获取淘宝的评论。需要注意的是,淘宝的反爬是很严的,需要登陆,对频率和速度也有限制,所以在爬取的量比较大的时候建议使用代理池和多cookie。

流程

这里,我们以一个随机商品为例,流程如下:

  • 根据商品详情页链接获取真实的评论请求url
  • 请求评论url,接收响应
  • 解析数据,获取评论总数和评论数据
  • 存储数据到本地
  • 根据评论总数构造循环翻页,重复2、3、4步

淘宝的评论是通过JS动态渲染出来的,并没有在初始请求的网页源码中,所以我们要找到发送新请求的url,这个并不难找。


右键f12进入检查,此时没有发送评论请求,评论并没有加载;当点击网页的评论按钮时,有新的请求被发送了,“feedRateList”开头的新请求就是我们要找的。从preview中可以看出,这是一个json,里面包含了评论和其它的数据。这里可以把整个json拿出来,但里面有很多其它keys,很多我并不知道含义,所以我只提取了自己感兴趣的数据。

详细代码

import re
import requests
import json
import math
import time
#import pymongo

class TaoBaoComment:
def __init__(self):
self.target_url = 'https://item.taobao.com/item.htm?spm=a219r.lm874.14.58.7cd87156tmSUG2&id=579824132873&ns=1&abbucket=18#detail'
self.raw_url = 'https://rate.taobao.com/feedRateList.htm?'
self.post_url = 'https://login.taobao.com/member/login.jhtml?'
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
'Cookie': 'cookie'#登陆后获取,也可以使用session登陆
}
self.item_id = self.parse_url(self.target_url)
#        self.session = requests.session()

def parse_url(self, url):
pattern = re.compile('.*?id=([0-9]+)&.*?', re.S)
result = re.findall(pattern, url)
return result[0]

#    def login_in(self):
#        data = {'TPL_username': 'xxx', 'TPL_password': 'xxx'}
#        post_resp = self.session.post(self.post_url, headers=self.headers, data=data)
#        print(post_resp.status_code)

def get_page(self, pagenum):
params = {
'auctionNumId': self.item_id,
'currentPageNum': pagenum
}
resp = requests.get(self.raw_url, params=params, headers=self.headers)
print(resp.status_code)
#        resp.encoding = resp.apparent_encoding
content = re.sub(r'[\n\r()]', '', resp.content.decode())
return content

def get_detail(self, content):
if
20000
content:
page=json.loads(content)
if page and ('comments' in page.keys()):
total=page['total']
comments = self.get_comment(page)
return comments, total

def get_comment(self, page):
if page and ('comments' in page.keys()):
detail_list = []
for comment in page['comments']:
details = {'date': comment['date']}
details['num'] = comment['buyAmount']

if comment['bidPriceMoney']:
details['amount']=comment['bidPriceMoney']['amount']

if comment['auction']['sku']:
details['sku']=comment['auction']['sku'].replace('&nbsp', '')

details['comment']=comment['content']
if comment['photos']:
details['photos']=[i['url'].replace('_400x400.jpg', '') for i in comment['photos']]

if comment['append']:
details['extra_comment']=comment['append']['content']
if comment['append']['photos']:
details['extra_photos']=[i['url'].replace('_400x400.jpg', '') for i in comment['append']['photos']]
details['dayAfterConfirm']=comment['append']['dayAfterConfirm']

detail_list.append(details)
return detail_list

def on_save(self, content):
if content:
with open('E:/spiders/taobao_comment/comment.txt', 'a', encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False))
f.write('\n')

def run(self):
#        self.login_in()
content = self.get_page(1)
comments, total = self.get_detail(content)
for comment in comments:
self.on_save(comment)
pagenum=math.ceil(total/20)
n = 2
while pagenum >= n:
content = self.get_page(2)
time.sleep(5)
comments, _ = self.get_detail(content)
for comment in comments:
self.on_save(comment)
print('page {} saved'.format(n))
n += 1

if  __name__ == '__main__':
comment = TaoBaoComment()
comment.run()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: