【问题标题】:BeautifulSoup not defined when called in function在函数中调用时未定义 BeautifulSoup
【发布时间】:2019-02-20 19:18:40
【问题描述】:

当我在函数内部调用 BeautifulSoup() 时,我的网络抓取工具正在抛出 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')

【问题讨论】:

  • 不是说Name url not defined吗?因为它没有在您的第二个示例中定义。
  • 编辑以反映我的代码
  • 您是否真的从您的代码中复制了示例?如果不是,请检查拼写错误(例如尝试区分大小写的搜索)
  • 请附上完整的错误信息。

标签: python beautifulsoup


【解决方案1】:

我猜你在做 BeautifulSoup 的一些拼写错误,它区分大小写。如果没有,请在代码中使用 requests 为:

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')

【讨论】:

    【解决方案2】:

    先将 BeautifulSoup 导入一个变量,然后再使用它。

        from bs4 import BeautifulSoup as yourVariable
    

    【讨论】:

    • 请不要只发布代码,添加描述以获得更多帮助
    猜你喜欢
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多