NameError:name' n'没有用BeautifulSoup定义解析

时间:2017-10-25 17:13:45

标签: python beautifulsoup

当我运行下面发布的python代码段时,我突然得到了NameError。我有类似的函数定义,基本上使用BS4进行网页抓取,但下面提到的当前函数会抛出此错误。

我已经在SO上研究了这个错误,并相应地添加了全局定义,但仍然没有解决这个问题。 任何帮助深表感谢。提前谢谢!

Python代码段:

def bcnews(self):
    global n, l
    bcheadline = requests.get("https://www.bleepingcomputer.com/")
    soup=BeautifulSoup(bcheadline.content, 'html.parser')
    for data in soup.find_all('div', class_="bc_banner_item cz-banner-item"):
        for item in soup.find_all('div', class_="bc_banner_caption"):
            n = (item.find('h4').contents[0])
            break
        for links in item.find_all('a'):
            l = (links.get('href'))
            break
        break
    return (n,l)

1 个答案:

答案 0 :(得分:0)

您的问题是从未达到n = ...作业。如果for循环没有任何要迭代的内容,就会发生这种情况:

>>> for i in []:  # empty list
...     n = i
...
>>> n
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

如果for方法调用返回空结果,则soup.find_all()循环无需迭代。

常见的解决方案是确保将某些内容分配给该名称,例如None

>>> n = None
>>> for i in []:  # empty list
...     n = i
...
>>> n is None  # nothing else was assigned
True

但是,在您的情况下,您根本不需要循环 。您可以使用CSS selector进行搜索,以找到嵌套选择器的第一个匹配

try:
    title = soup.select_one('div.bc_banner_item div.bc_banner_caption h4').get_text()
    link = soup.select_one('div.bc_banner_item a[href]').get('href')
    return title, link
except AttributeError:
    return None, None

捕获AttributeError异常会处理根本没有匹配元素的情况(因此.get_text.get属性查找将失败。