当我在函数内部调用BeautifulSoup()时,我的Web抓取工具会抛出NameError: name 'BeautifulSoup' is not defined
,但当我在函数外部调用它并将Soup作为参数传递时,它会正常工作。
这是工作代码:
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))
但是当我在函数中移动BeautifulSoup调用时,我得到了错误。
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')
答案 0 :(得分:0)
我猜您在执行BeautifulSoup的一些拼写错误,它区分大小写。如果没有,请在代码中使用以下请求:
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')
答案 1 :(得分:0)
先将 BeautifulSoup 导入到一个变量中,然后再使用。
from bs4 import BeautifulSoup as yourVariable