none函数python_如何防止python函数返回none

这篇博客讨论了如何使用BeautifulSoup库解析HTML表格,特别是通过重构多重if语句来提高代码可读性。作者引入了一个名为html_check的辅助函数,该函数查找特定文本并返回相邻的td元素内容。然而,当找不到匹配项时,函数返回None,导致不必要的输出。作者寻求解决方案以确保函数仅在找到匹配项时返回值。
摘要由CSDN通过智能技术生成

我正在用这样漂亮的汤解析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条件满足时,才能使该函数返回值吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值