在尝试使用BeautifulSoup从一些网页获取信息时,有许多重叠的代码,所以我想让它成为一个函数,但我想在find_all
和select
等bs
中调用函数。我该怎么做呢?
import requests
from bs4 import BeautifulSoup
def test(url, function, *lst):
result = requests.get(url)
soup = BeautifulSoup(result.text, "lxml")
result = soup.function(*lst)
return
test('www', find_all)
test('www', select_one)
NameError: name 'find_all' is not defined
如果您像这样调用函数(您可能需要提供额外的参数)
test('www','find_all')
你可以调用方法"find_all"在函数中,如:
result = getattr(soup, function)(*lst)