为什么偶尔会出现TypeError?

2024-10-01 09:23:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我的python报废程序遇到了TypeError

这是我的密码:

from bs4 import BeautifulSoup
import requests, feedparser

cqrss = feedparser.parse('https://www.reddit.com/r/pics/new.rss')

for submission in cqrss.entries:
    folder_name = submission.title #use for create folder
    reddit_url = submission.link
    source = requests.get(reddit_url)
    plain_text = source.content
    soup = BeautifulSoup(plain_text, 'lxml')
    title = soup.find('a', 'title may-blank outbound', href=True)
    if 'imgur.com' in title['href']:
        imgur_link = title['href']
    print(imgur_link)

错误:

if 'imgur.com' in title['href']:

TypeError: 'NoneType' object is not subscriptable

我做错了什么


Tags: inimportcomsubmissionfortitlelinkrequests
1条回答
网友
1楼 · 发布于 2024-10-01 09:23:38

find对某些数据“失败”(即找不到任何内容),并返回None

if title and 'imgur.com' in title['href']:
    imgur_link = title['href']
    print(imgur_link)

应该有用

请注意,printif子句下移动,因为如果数据不在那里,调用它显然没有意义

相关问题 更多 >