我想創建一個函數,返回一個字典並使用它3次,然後將返回的字典加入到1中。然後將該字典作爲值分配給另一個字典。但是print(all_dict)只返回1個字典。如果我嘗試打印(get_dict(f1)),我會得到下面的Traceback。如果不是每次調用同一個函數3次,我都用每個函數中的相同命令分別定義每個函數,我可以得到我想要的。但我希望找到更簡潔的方式來編寫代碼。Python函數使用3次,但只返回一次
您可以找到表這裏的HTML:https://github.com/Tokaalmighty/topmover_table_html/blob/master/html
Traceback (most recent call last):
File "week4_1.py", line 55, in <module>
print(get_dict(f1))
File "week4_1.py", line 23, in get_dict
bold=topmovers.find_all('b')
AttributeError: 'NoneType' object has no attribute 'find_all'
這裏是我的函數的代碼,我如何想加入3個字典爲1:
def get_dict(f1):
soup=bs(f1,'html.parser')
topmovers=soup.find('table'{'class':'topmovers'})
bold=topmovers.find_all('b')
…
…
return final
all_dict={}
result = {**get_dict(f1), **get_dict(f2), **get_dict(f3)}
all_dict['result']=result
print(all_dict)
print(get_dict(f1))
你的錯誤是由'topmovers = soup.find('table',{'class':'topmovers'})'返回'None'造成的。到目前爲止,這個問題不在你的代碼中,而是你缺乏錯誤處理。您無法針對「無」調用方法。 –
但它不會返回一個無,如果我完全鍵入3個函數.. – Tokaalmighty