NameError: 名称 'feed' 未定义

-1 投票
2 回答
1346 浏览
提问于 2025-04-18 10:32

我有两个代码片段,来自一个网络研讨会(分别是第7和第8张幻灯片)

一个代码片段是用来找到一个想要的URL我测试过了,确实有效

def SECdownload(year, month):
    import os
    from urllib.request import urlopen
    root = None
    feedFile = None
    feedData = None
    good_read = False
    itemIndex = 0
    edgarFilingsFeed = 'http://www.sec.gov/Archives/edgar/monthly/xbrlrss-' + str(year) + '-' + str(month).zfill(2) + '.xml'
    print( edgarFilingsFeed )
    if not os.path.exists( "sec/" + str(year) ):
        os.makedirs( "sec/" + str(year) )
    if not os.path.exists( "sec/" + str(year) + '/' + str(month).zfill(2) ):
        os.makedirs( "sec/" + str(year) + '/' + str(month).zfill(2) )
    target_dir = "sec/" + str(year) + '/' + str(month).zfill(2) + '/'
    try:
        feedFile = urlopen( edgarFilingsFeed ) # urlopen will not work (python 3) needs from urllib.request import urlopen
        try:
            feedData = feedFile.read()
            good_read = True
        finally:
            feedFile.close()
    except HTTPError as e:
        print( "HTTP Error:", e.code )

而第二个代码片段是用来解析RSS Feed,以找到ZIP文件名:

#Downloading the data - parsing the RSS feed to extract the ZIP file enclosure filename
# Process RSS feed and walk through all items contained
for item in feed.entries:
    print( item[ "summary" ], item[ "title" ], item[ "published" ] )
    try:
        # Identify ZIP file enclosure, if available
        enclosures = [ l for l in item[ "links" ] if l[ "rel" ] == "enclosure" ]
        if ( len( enclosures ) > 0 ):
            # ZIP file enclosure exists, so we can just download the ZIP file
            enclosure = enclosures[0]
            sourceurl = enclosure[ "href" ]
            cik = item[ "edgar_ciknumber" ]
            targetfname = target_dir+cik +' - ' +sourceurl.split('/')[-1]
            retry_counter = 3
            while retry_counter > 0:
                good_read = downloadfile( sourceurl, targetfname )
                if good_read:
                    break
                else:
                    print( "Retrying:", retry_counter )
                    retry_counter -= 1
    except:
        pass

但是每当我尝试运行第二个模块时,我就会遇到:

Traceback (most recent call last):
  File "E:\Py_env\df2.py", line 3, in <module>
    for item in feed.entries:
NameError: name 'feed' is not defined

我在网络研讨会上到底理解错了什么呢?如果我必须定义feed,我真的不知道该怎么做,而且还要和第一个代码片段提供的数据保持逻辑关联

(顺便说一下,这是一个来自知名软件供应商的网络研讨会,怎么可能会有错误呢?我一定是哪里做错了…)

2 个回答

2

这个问题就像错误信息所说的那样:在第二段代码执行的时候,你没有定义任何叫做 feed 的变量,所以它找不到。要么是他们的代码漏掉了什么,要么就是你错过了一个很重要的部分。

另外,这段代码的格式看起来很糟糕,根本不是标准的Python写法。你可能更应该找一个新的代码片段。

1

这是从一个评论迁移过来的内容。

正如你输出的结果所示,你注意到feed没有被定义,也没有在幻灯片中展示出来。看起来幻灯片的分享者希望你能进行一些逻辑上的推理,他们在右侧栏中提到feedparser是解析... 数据源(RSS源)的一个简单方法。

所以他们希望你能利用在第一个函数中找到的feedData,并把它放入feedparser中的一个方法里。

在网上的各种示例中(比如这个文档),你可以看到如何从你得到的字符串中做到这一点:

>>> import feedparser
>>> rawdata = """<rss version="2.0">
<channel>
<title>Sample Feed</title>
</channel>
</rss>"""
>>> d = feedparser.parse(rawdata)
>>> d['feed']['title']
u'Sample Feed'

利用这个,我相信你能看出该怎么做(而不是我告诉你)。

正如@PatrickCollins所指出的,这些示例对于Python来说有点糟糕,但这不应该妨碍你学习。

撰写回答