python 函数返回none,如何防止Python函数返回None

我正在使用BeautifulSoup解析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语句重构为一个函数:

def html_check(td, text):

if td.text == text:

value = td.find_next('td').text

return value

像这样被称为:

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条件时才返回值?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值