爬虫时出现部分结果报错'NoneType' object is not subscriptable,如何解决?

问题遇到的现象和发生背景

爬虫时出现的错误

问题相关代码,请勿粘贴截图
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)

运行结果及报错内容

img

我的解答思路和尝试过的方法

去掉["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 ""

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632