挪威森林湖畔的水手 2022-04-25 00:43 采纳率: 75%
浏览 512
已结题

爬虫时出现部分结果报错'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"]不会报错,但不是我想要的结果

我想要达到的结果

消除报错,并能运行此代码。

  • 写回答

2条回答 默认 最新

  • 关注

    '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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 4月25日
  • 已采纳回答 4月25日
  • 创建了问题 4月25日

悬赏问题

  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗