我用beauthulsoup解析HTML表,如下所示:
for tr in table_body.find_all('tr'):
for td in tr:
if td.text == 'Description':
description = td.find_next('td').text
if td.text == 'Category':
category = td.find_next('td').text
if td.text == 'Department':
department = td.find_next('td').text
if td.text == 'Justification':
justification = td.find_next('td').text
print(description, category, department, justification)
我将多个if
语句重构为一个函数:
这叫做:
for tr in table_body.find_all('tr'):
for td in tr:
description= html_check(td, 'Description')
category = html_check(td, 'Category')
department = html_check(td, 'Department')
justification = html_check(td, 'Justification')
print(description, category, department, justification)
我的问题是,当函数html_check
找不到匹配项时,它将返回None
,这将被打印出来。这是不可取的。在
有没有办法让这个函数只在满足if条件时才返回值?在
您可以尝试只打印那些值匹配的值。在
如果在退出函数调用时没有指定返回,Python将始终返回
None
。您的选择是:None
,则忽略该函数选项1(不满足条件时返回其他内容):
选项2(如果返回
^{pr2}$None
,则忽略函数):可以指定一个默认值,以便在没有元素匹配的情况下返回。 比如:
此外,您还可以通过参数指定默认值,这有点像:
^{pr2}$然后使用它,就像:
相关问题 更多 >
编程相关推荐