在BeautifulSoup文档中,定义了一个函数如下:
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id')
然后作为参数传递给函数:find_all()
:
soup.find_all(has_class_but_no_id)
令我惊讶的是它有效。我真的不知道这里的机制是如何工作的,这个函数 (has_class_but_no_id
) 怎么会在没有参数的情况下为 find_all()
函数返回一个值?
最佳答案
has_class_but_no_id
在您将其传递给 find_all()
时未执行。
find_all
多次执行对 has_class_but_no_id
的调用,当时将其作为“tag”的值传递给它。这种模式利用了以下事实:在 Python 中,函数是所谓的一阶对象 - 它们作为对象存在,您可以在变量中传递它们。
这允许函数接受其他函数并在稍后运行它们 - 就像 BeautifulSoup 在这里做的那样。
尝试一个实验:
def say_something(something_to_say):
print something_to_say
def call_another_function(func, argument):
func(argument)
call_another_function(say_something, "hi there")
以上答案摘自this Reddit post .
此外,请参阅 source code for find_all , 和 call .
关于python - 将函数作为参数传递 - BeautifulSoup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43249828/