0

While trying to get information from some web pages using BeautifulSoup, there are many overlapping codes, so I want to make it a function, but I want to call a function within bs such as find_all and select. How can I do it?

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

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 2
    Does this answer your question? [Calling a function of a module by using its name (a string)](https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string) – mkrieger1 Jul 01 '22 at 13:14

1 Answers1

1

If you call the function like (you may have to provide additional arguments)

test('www','find_all')

You can call the method "find_all" in the function like:

result = getattr(soup, function)(*lst)
Michael Butscher
  • 10,028
  • 4
  • 24
  • 25