2017-10-04 63 views
0

我的python報廢程序正在運行TypeError。爲什麼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 

我做了什麼錯?

+3

這意味着標題中的'href'鍵是None(空)。因此,檢查它是否爲空,然後獲取鏈接,如果它不爲null。 – Steampunkery

+0

@Steampunkery我認爲關於'title'的投訴不是可以訂購的,意味着第一個地方沒有'href'鍵,甚至不會丟失,它不能存在。如果'href'下的值是'None',我認爲它會說這個值是* non-iterable *。 – luk32

+0

@ luk32如果鑰匙不存在就不會拋出鑰匙錯誤嗎? – Steampunkery

回答

2

find對某些數據「失敗」(即找不到任何東西)並返回None

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

應該工作。

請注意,print已根據if條款進行了移動,因爲如果數據不存在,顯然無法調用它。

相關問題