【问题标题】:Getting 'global name not defined' error in Python using scrapy使用scrapy在Python中获取“未定义全局名称”错误
【发布时间】:2017-03-27 00:29:45
【问题描述】:

我一直在从 Ryan Mitchell 的一本名为 Web Scraping with Python 的书中学习 scrapy。书中有一段代码可以从网站获取外部链接。即使我使用与书中相同的代码(我对它所做的唯一一件事就是将 'urllib.request' 更改为 'urllib2'),我仍然收到相同的错误。 Python 版本是 2.7.12。 这是错误:

File "test.py", line 28, in <module>
getAllExternalLinks("http://www.oreilly.com")
File "test.py", line 16, in getAllExternalLinks
internalLinks = getInternalLinks(bsObj, splitAddress(siteUrl)[0])
NameError: global name 'getInternalLinks' is not defined

这是我正在使用的代码。

from urllib2 import urlopen
from urlparse import urlparse
from bs4 import BeautifulSoup
import re
allExtLinks = set()

allIntLinks = set()

def getAllExternalLinks(siteUrl):

    html = urlopen(siteUrl)

    bsObj = BeautifulSoup(html)

    internalLinks = getInternalLinks(bsObj,splitAddress(siteUrl)[0])

    externalLinks = getExternalLinks(bsObj,splitAddress(siteUrl)[0])

    for link in externalLinks:

        if link not in allExtLinks:

            allExtLinks.add(link)

            print(link)

    for link in internalLinks:

        if link not in allIntLinks:

            print("About to get link: "+link)

            allIntLinks.add(link)

            getAllExternalLinks(link)

getAllExternalLinks("http://www.oreilly.com")

【问题讨论】:

  • 我不知道您使用的是什么版本的书,也不知道您在哪里复制了这个 sn-p - 但它缺少一半的代码。完整的例子是available on github

标签: python-2.7 web-scraping scrapy web-crawler scrapy-spider


【解决方案1】:

在编译之前仔细阅读示例代码。 看,您的代码中没有getInternalLinks() 函数。

【讨论】:

    猜你喜欢
    • 2019-01-22
    • 2013-07-03
    • 1970-01-01
    • 2010-10-07
    • 2019-09-09
    • 2012-03-28
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    相关资源
    最近更新 更多