4

My web scraper is throwing NameError: name 'BeautifulSoup' is not defined when I call BeautifulSoup() inside my function, but it works normally when I call it outside the function and pass the Soup as an argument.

Here is the working code:

from teams.models import *
from bs4 import BeautifulSoup
from django.conf import settings
import requests, os, string

soup = BeautifulSoup(open(os.path.join(settings.BASE_DIR, 'revolver.html')), 'html.parser')

def scrapeTeamPage(soup):
    teamInfo = soup.find('div', 'profile_info')
...
print(scrapeTeamPage(soup))

But when I move the BeautifulSoup call inside my function, I get the error.

from teams.models import *
from bs4 import BeautifulSoup
from django.conf import settings
import requests, os, string

def scrapeTeamPage(url):
    soup = BeautifulSoup(open(os.path.join(settings.BASE_DIR, url)), 'html.parser')
    teamInfo = soup.find('div', 'profile_info')
Anders Juengst
  • 39
  • 1
  • 1
  • 4

2 Answers2

4

I guess you are doing some spelling mistake of BeautifulSoup, its case sensitive. if not, use requests in your code as:

from teams.models import *
from bs4 import BeautifulSoup
from django.conf import settings
import requests, os, string

def scrapeTeamPage(url):
    res = requests.get(url)
    soup = BeautifulSoup(res.content, 'html.parser')
    teamInfo = soup.find('div', 'profile_info')
0

Import BeautifulSoup first into a variable and then use it.

    from bs4 import BeautifulSoup as yourVariable
Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44
王淳龙
  • 47
  • 1
  • 3