You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在自定义函数中动态调用BeautifulSoup对象的内置方法

报错原因

代码存在三处核心问题:

  • find_all、select_one是BeautifulSoup实例的绑定方法,并非全局作用域下的独立函数,直接在全局位置传参时解释器找不到对应定义,抛出NameError: name 'find_all' is not defined异常。
  • 函数内soup.function(*lst)的写法是固定调用soup对象上名为function的属性,不会匹配传入的方法参数,无法实现动态调用逻辑。
  • 原函数末尾return未携带返回值,即使解析逻辑正常也无法拿到结果。
正确实现方案

使用Python内置getattr()方法动态获取BeautifulSoup实例上的对应解析方法,调用时仅需传入方法名字符串即可,兼容所有BeautifulSoup内置解析方法,同时支持位置参数、关键字参数传递:

import requests
from bs4 import BeautifulSoup

def parse_page(url, parse_method, *args, **kwargs):
    # 发起请求,添加超时配置避免卡死
    resp = requests.get(url, timeout=10)
    # 自动识别响应编码,避免乱码
    resp.encoding = resp.apparent_encoding
    soup = BeautifulSoup(resp.text, "lxml")
    # 动态获取实例对应的解析方法
    method = getattr(soup, parse_method)
    # 执行解析并返回结果
    return method(*args, **kwargs)

# 调用示例
if __name__ == "__main__":
    # 替换为带http/https协议的完整目标URL
    target_url = "https://example.com"
    # 调用find_all查找所有class为item的div标签
    div_items = parse_page(target_url, "find_all", "div", class_="item")
    # 调用select_one查找id为main的首个元素
    main_content = parse_page(target_url, "select_one", "#main")
    # 调用select查找所有列表项下的链接
    link_list = parse_page(target_url, "select", "ul li a")
可选实现方式

如果不想传方法名字符串,也可以直接传入BeautifulSoup类的未绑定方法,调用时实例会自动作为self参数传入,写法如下:

# 直接传入类层面的方法引用
div_items = parse_page(target_url, BeautifulSoup.find_all, "div", class_="item")

注意:传入URL时必须携带http://或https://协议头,否则requests会抛出地址无效错误。

内容的提问来源于stack exchange,提问作者KimGyeongMin-KR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 01:27:27