python 爬虫基础知识,返回值为json数据的 爬虫原代码

import urllib.request
import urllib.parse
import json
import re
import jsonpath




'''
接口
https://rate.taobao.com/feedRateList.htm?auctionNumId=559141739630&userNumId=100340983¤tPageNum=3&pageSize=20
'''


items_list = []


def main():
# 在这里搞一个循环,爬取多页的评论内容
url = 'https://rate.taobao.com/feedRateList.htm?auctionNumId=559141739630&userNumId=100340983¤tPageNum=1&pageSize=20'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
}
request = urllib.request.Request(url=url, headers=headers)
json_text = urllib.request.urlopen(request).read().decode()

# 去除json格式字符串两边的非法字符
json_text = json_text.strip('() \n\t\r')
# print(json_text)
# 将json两边的小括号干掉,通过正则去除
# json_text = re.sub(r'\(', '', json_text)
# json_text = re.sub(r'\)', '', json_text)
# print(json_text)
# exit()
# 将json格式字符串转化为python对象
obj = json.loads(json_text)
# print(obj)
# 抓取评论内容
# 用户头像、用户名、评论内容、评论时间、手机类型
# 首先取出comments这个列表
comments_list = obj['comments']
# 遍历这个列表,依次提取每一条评论
for comment in comments_list:
# 用户头像
user = jsonpath.jsonpath(comment, '$..user')[0]
face = 'http:' + user['avatar']
# 用户名
name = user['nick']
# 评论内容
ping_content = comment['content']
# 评论时间
ping_time = comment['date']
# 手机信息
info = jsonpath.jsonpath(comment, '$..sku')[0]
# 将评论信息保存到字典中
item = {
'用户头像': face,
'用户名': name,
'评论': ping_content,
'时间': ping_time,
'信息': info,
}
items_list.append(item)


if __name__ == '__main__':
main()


string = json.dumps(items_list, ensure_ascii=False)
# 保存到文件中
with open('ping.txt', 'w', encoding='utf8') as fp:
fp.write(string)

你可能感兴趣的:(python爬虫)