UnboundLocalError - 在范围内,全局或非本地分配的变量不起作用

时间:2017-07-24 21:23:18

标签: python python-2.7 scrapy scrapy-spider

我已经尝试阅读有关UnboundLocalError的先前答案,但是我找不到与我类似的任何内容。我试着设置非本地以及没有运气的全局。

我收到 UnboundLocalError:本地变量' product_color'在运行这段代码时,在赋值之前引用,但是,如果我只运行第一个for循环,则不会出现错误。我不明白为什么我不能在没有得到UnboundLocalError的情况下做同样的事情。

def parse_product(self, response):
    product_category = response.meta.get('Category')
    product_title = response.meta.get('Product Title')
    product_price = response.meta.get('Product price')
    product_url = response.meta.get('Product URL')
    main_image_url = response.meta.get('Main image URL')

    product_description = response.xpath('//p[@class="product-detail-description-text"]/text()').extract()

    images = response.xpath('//div[@class="product-detail-thumbnails"]')

    for image in images:
        alt_image_url = image.xpath('ul/li/img/@src').extract()

    colors = response.xpath('//ul[@class="input clearfix"]')

    for color in colors:
        product_color = color.xpath('li/a/@title').extract()

    yield {'Product Category': product_category, 'Product Title': product_title, 'Product price': product_price, 'Product URL': product_url, 'Main image': main_image_url, "Alt images": alt_image_url, 'Description': product_description, 'Product color': product_color}

更新:完整错误消息

    Traceback (most recent call last):
    File "/usr/local/lib/python2.7/site-packages/scrapy/utils/defer.py", line 102, in iter_errback
yield next(it)
    File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/offsite.py", line 29, in process_spider_output
for x in result:
    File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/referer.py", line 339, in <genexpr>
return (_set_referer(r) for r in result or ())
    File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/urllength.py", line 37, in <genexpr>
return (r for r in result or () if _filter(r))
    File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/depth.py", line 58, in <genexpr>
return (r for r in result or () if _filter(r))
    File "/Users/stefanjohansen/Projects/Python/hm/hm/spiders/products.py", line 46, in parse_product
yield {'Product Category': product_category, 'Product Title': product_title, 'Product price': product_price, 'Product URL': product_url, 'Main image': main_image_url, "Alt images": alt_image_url, 'Description': product_description, 'Product color': product_color}
    UnboundLocalError: local variable 'product_color' referenced before assignment

0 个答案:

没有答案