如何防止Python返回非函数

2024-05-23 18:05:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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语句重构为一个函数:

^{pr2}$

这叫做:

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


Tags: 函数textinforifhtmlcheckdescription
3条回答

您可以尝试只打印那些值匹配的值。在

for tr in table_body.find_all('tr'): 
            fields = ['Description','Category','Department','Justification']
            for td in tr:
                print (['{}:{}'.format(i,html_check(td,i)) for i in fields if html_check(td,i)])

如果在退出函数调用时没有指定返回,Python将始终返回None。您的选择是:

  • 如果不满足条件,则返回其他内容。在
  • 如果函数返回None,则忽略该函数

选项1(不满足条件时返回其他内容):

 def html_check(td, text):
     if td.text == text:
        value = td.find_next('td').text
        return value
     return "no value found"

选项2(如果返回None,则忽略函数):

^{pr2}$

可以指定一个默认值,以便在没有元素匹配的情况下返回。 比如:

def html_check(td, text):
        if td.text == text:
            value = td.find_next('td').text
            return value
        return "Default Value"

此外,您还可以通过参数指定默认值,这有点像:

^{pr2}$

然后使用它,就像:

for tr in table_body.find_all('tr'):      
            for td in tr:  
                description= html_check(td, 'Description', 'Default Description')
                category = html_check(td, 'Category','Default Category')
                department = html_check(td, 'Department', 'Default Department')
                justification = html_check(td, 'Justification', 'Default Justification')
print(description, category, department, justification)

相关问题 更多 >