AJAX网页,爬取指定电影下评论内容及用户信息。报错"json.decoder.JSONDecodeError: Expecting value"

这里以优酷《哪吒》的用户评论为目标

报错信息如下:

"""raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)"""

最终原因折磨了我好久,是因为json中没有圆括号这种东西,本次事例中的圆括号又难以去掉

b话少说,先上代码

import requests
import json
import re

# 构建评论列表的URL,接下来用以得到杰森格式的评论内容
comment_url = "https://p.comments.youku.com/ycp/comment/pc/commentList?jsoncallback=n_commentList&\
app=100-DDwODVkv&objectId=1097963004&objectType=1&listType=0&current\
Page={}&pageSize=30&sign=8fc6ac73638d4f0263358f1ae323489b&time=1572784759".format(input("请输入,来获取本页的评论:"))

# 得到json数据
head = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) \
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"}
html = requests.get(comment_url, headers=head).text

html_json = re.findall("n_commentList(.*)", html, re.S)[0].strip(")").replace("(", "")
print(len(html_json))

# 转化为json后,通过debug调试,发现是一个由列表和字典混合组成多层嵌套的字典,需要层层挖掘信息
json_content = json.loads(html_json)
content_data = json_content["data"]
comment_data = content_data["comment"]
number = 1
for each_comment in comment_data:
    print("第{}条评论\n".format(number), "账号:", each_comment["userId"])
    print("用户名:", each_comment["user"]["userName"])
    if len(each_comment["user"]["vipInfo"]) == 0:
        print("VIP等级:非会员")
    else:
        print("VIP等级:", each_comment["user"]["vipInfo"]["name"])
    print("评论内容:".format(number), each_comment["content"], "\n", "--"*25)
    number += 1

过程:
首先在电影页面往下滑,评论将会加载

的确在源代码中我们可以看到用户评论,但是用户信息将无能为力

这里我使用Chrome浏览器,监控network的变化
我们首先要找到:
在这里插入图片描述
没错,就是评论列表,comment是评论的意思
接着我们在新页面中打开他的URL
有基础的朋友能看出来,这是一个json格式

在这里插入图片描述
通过对比多个页面的URL,发现他们并没有很大的差别,只有页数产生了变化,如我的代码中使用format来加入页码。

可以看到json被圆括号包裹了,一开始我是这样写的
非贪心算法

re.findall("n_commentList(.*?)", html, re.S)

实际上这样什么也提取不出来!!!
首先这里的括号并不会作为标识元素,也就是说你提取的文本依然会有括号
其次非贪心算法将会提取最短字符串,而且本段文本又是以")"为结尾,所以提取公式中将会没有结尾,那么非贪心算法什么也不会提取

作如下修改

re.findall("n_commentList(.*)", html, re.S)[0].strip(")").replace("(", "")

终于可以成功转换为json
用户信息一览无余:
在这里插入图片描述
每一条展开都很复杂
在这里插入图片描述

发布了28 篇原创文章 · 获赞 74 · 访问量 1661

猜你喜欢

转载自blog.csdn.net/CxsGhost/article/details/103429976