爬虫时出现的错误
for comment in comments:
uersname=comment.find("a")["title"] and comment.find("a")["title"] or ""
rating=comment.find("span",{"class":"rating"})["title"] and comment.find("span",{"class":"rating"})["title"] or""
time=comment.find("span",{"class":"comment-time"}).text.split()[0]
content=comment.find("span",{"class":"short"}).text and comment.find("span",{"class":"short"}).text or ""
vote=comment.find("span",{"class":"vote-count"}).text and comment.find("span",{"class":"vote-count"}).text or ""
data=uersname+";"+time+";"+content+";"+vote+"\n"
print(rating)
去掉["title"]不会报错,但不是我想要的结果
消除报错,并能运行此代码。
'NoneType' object is not subscriptable
这个错误是comment.find("span",{"class":"rating"})没有获取到元素,返回了None
你print(comment)输出下comment看看是不是有<span class="rating">
标签, rating有没有写错
如果允许comment中没有<span class="rating">
标签,可以这样判断
rating=comment.find("span",{"class":"rating"}) and comment.find("span",{"class":"rating"}).get("title") or ""
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!