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

爬虫时出现部分结果报错'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日

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度