检查python对象是否为“无”不起作用
我使用beautifulsoup和下面的代码块来检查这个HTMLTR对象中是否包含th检查python对象是否为“无”不起作用,python,beautifulsoup,Python,Beautifulsoup,我使用beautifulsoup和下面的代码块来检查这个HTMLTR对象中是否包含th if tr.find('th') is not None: result[tr.find('th').text] = tr.find('td').text 但它总是输入if块并返回属性错误“'NoneType'对象没有属性'text'” 我做错了什么?您有两个不同的tr.find()调用,一个用于'th',另一个用于'td'。后者也可以返回None,但您不需要进行测试,因此tr.fin
if tr.find('th') is not None:
result[tr.find('th').text] = tr.find('td').text
但它总是输入if块并返回属性错误“'NoneType'对象没有属性'text'”
我做错了什么?您有两个不同的
tr.find()
调用,一个用于'th'
,另一个用于'td'
。后者也可以返回None
,但您不需要进行测试,因此tr.find('td')。text
可以引发AttributeError
异常
您需要测试这两个结果。如果缺少td
单元格,可能存储空字符串或其他默认值
header, cell = tr.find('th'), tr.find('td')
if header is not None:
result[header.text] = cell.text if cell is not None else ''
有两个不同的
tr.find()
调用,一个用于'th'
,另一个用于'td'
。后者也可以返回None
,但您不需要进行测试,因此tr.find('td')。text
可以引发AttributeError
异常
您需要测试这两个结果。如果缺少td
单元格,可能存储空字符串或其他默认值
header, cell = tr.find('th'), tr.find('td')
if header is not None:
result[header.text] = cell.text if cell is not None else ''
如果tr.find('td')
是None
,怎么办?如果tr.find('td')
是None
?