gpt4 book ai didi

python - 如何创建在偶尔设置非类型的功能输入中发生的 NoneType 错误解决方法

转载 作者:太空宇宙 更新时间:2023-11-04 02:05:01 24 4
gpt4 key购买 nike

我有一种情况,即输入代码的数据集会产生 NoneType 错误。在尝试了几个变体来解决错误后,我不确定如何修改代码来做到这一点。这是追溯。

Traceback (most recent call last):
File "A:\anoth\test.py", line 64, in <module>
pretty_print(master)
File "A:\anoth\\test.py", line 53, in pretty_print
categories = find_elms(soup, 'div', {'id': 'categories'})
File "A:\anoth\\test.py", line 37, in find_elms
for region in regions:
TypeError: 'NoneType' object is not iterable

当 NoneType 数据进入代码时,下面的 if-then 循环没有起作用。

regions = soup.find(tag, attribute)
print('this ' + str(regions))
for region in regions: #this works for portions of the data set
if [elm.text for elm in regions.find_all('a')] is None:
return []
else:
return [elm.text for elm in regions.find_all('a')]

return []

有什么想法吗?

最佳答案

你的代码不起作用的原因是因为 regions 在某些时候是 None,而你试图在你的 for 循环中迭代 None,因此错误'NoneType' 对象不可迭代

regions = soup.find(tag, attribute)  #<------ this is returning None
print('this ' + str(regions))
for region in regions: #<-- you can't take a region in regions, when regions is None
if [elm.text for elm in regions.find_all('a')] is None:
return []
else:
return [elm.text for elm in regions.find_all('a')]

return []

你可以在里面添加一个try except:

try:
regions = soup.find(tag, attribute)
print('this ' + str(regions))
for region in regions: #this works for portions of the data set
if [elm.text for elm in regions.find_all('a')] == []:
return []
else:
return [elm.text for elm in regions.find_all('a')]

except:
print ('regions is NoneType object')
return []

关于python - 如何创建在偶尔设置非类型的功能输入中发生的 NoneType 错误解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54905615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com