0

更新: Woobleのコメントに応じて、forの前に「sector = None」を追加すると、単に「None」が返されます。問題は、forループの変数が返されないことだと思います。

以下は、コードの無関係に見える部分を変更した最近まで、正常に実行されていた関数の一部です。

#->最近変更したのは、returnステートメントに「stockurl」を追加することだけでした。

UnboundLocalErrorが発生します:割り当ての前に参照されるローカル変数「sector」、「return」行を参照

for sec in root.xpath(r'''//a[re:match(@href, "http://biz.yahoo.com/p/[0-9]{1}conameu.html")]''',
                namespaces={'re': 'http://exslt.org/regular-expressions'}):
    sector = sec.text
    #print "Sector: " + sector

for ind in root.xpath(r'''//a[re:match(@href, "http://biz.yahoo.com/ic/[0-9]{1,9}.html")]''',
        namespaces={'re': 'http://exslt.org/regular-expressions'}):
    industry = ind.text
    #print "Industry: " + industry

#index          --> don't populate here
#followers  --> don't populate here

return a, b, c, d, e, f, stockurl, sector, industry
    #--> the only part I had changed recently was adding "stockurl" to the function
4

1 に答える 1

5

エラー メッセージを見て、逆方向に作業してみましょう。

割り当て前に参照されるローカル変数「セクター」

これは、参照してsectorいるがsector、オブジェクトに割り当てられていない、またはバインドされていないことを意味します。

への唯一の割り当てsectorは、 for の本体内にありloopます。ということで、明らかにforループの本体が入っていませんでした。root.xpath()これは、 への呼び出しが空の反復可能なオブジェクトを返す場合にのみ発生します。

于 2012-05-12T23:28:23.460 に答える