python - 将函数作为参数传递 - BeautifulSoup

标签 python beautifulsoup

在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/

相关文章:

python-3.x - 无法使用 robobrowser 提交表单。无效提交错误

python - Beautiful Soup For 循环给了我单独的列表,但是需要一个数据框

python - 在数据帧列中填充键入 NA 的字符串时出错

python - networkx 从 python 字典设置节点属性

python - 将高斯总和转化为快速 Numpy?

Python BeautifulSoup 在写入文件时创建奇怪的\xe2 unicode 字符

python - 我怎样才能刮掉所有击球手的名字?

用于即时键迭代的 python 列表与元组

python - 优化海量python字典解析,多线程

python - 使用 Beautiful Soup Python 进行网页抓取