import bs4 import BeautifulSoup
file = open(".baidu.html","rb") # 打开html文档
html = file.read().decode("utf-8") # 读取html文档,以字符串形式传递给html变量
bs = BeautifulSoup(html, "html.parser") # 使用BeautifulSoup解析html
def name_is_exists(tag):
return tag.has_attr("href") # 如果标签里存在“href”则返回True,否则返回False
t_list = bs.find_all(name_is_exists) # 调用函数,此处为函数指针
for item in t_list:
print(item)
bs.find_all是逐个标签的匹配,每匹配一个标签,都会调用name_is_exists函数,然后通过name_is_exists函数的作用,判断此标签内是否存在 “href”。 若存在,则匹配正确,将此标签赋值给t_list列表。从第一个开始,一直匹配到最后一个标签。
其实,在每次调用name_is_exists的时候,就把此次所匹配的标签传递给tag。
C语言中的回调函数示例:
#include<iostream>
using namespace std;
int computer(int a, int b, int(*func)(int, int)) {
return func(a, b);
}
int max(int a, int b) {
return (a > b ? a : b);
}
int min(int a, int b) {
return (a > b ? b : a);
}
int sum(int a, int b) {
return a + b;
}
int main() {
int a, b, res;
cout << "请输入整数a:"; cin >> a;
cout << "请输入整数b:"; cin >> b;
res = computer(a, b, &max);
cout << "Max of " << a << " and " << b << " is " << res << endl;
res = computer(a, b, &min);
cout << "Min of " << a << " and " << b << " is " << res << endl;
res = computer(a, b, &sum);
cout << "Sum of " << a << " and " << b << " is " << res << endl;
return 0;
}