python - 在函数中调用时未定义 BeautifulSoup

标签 python beautifulsoup

当我在函数内部调用 BeautifulSoup() 时,我的网络抓取工具抛出 NameError: name 'BeautifulSoup' is not Define ,但当我在函数外部调用它并将 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')

最佳答案

我猜你犯了一些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')

关于python - 在函数中调用时未定义 BeautifulSoup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52358022/

相关文章:

Python 2.7,z分数计算

python - 创建多个具有不同名称的空列表

python - BeautifulSoup 找到 nextClass

python - 编写可维护的网络抓取工具的最佳实践是什么?

Python beautifulsoup - 获取输入值/TypeError : 'NoneType' object is not subscriptable

python - numpy.subtract 但仅直到差异达到阈值 - 用阈值替换小于该值的数字

python - 测试docker容器中的Python mqtt客户端连接到mqtt代理docker容器

python - 为什么 admin.py 从未加载?

Python - Beautiful Soup,如何获取标签的第一个值

Python漂亮的汤表单输入解析