【问题标题】:Local variable 'links' referenced before assignment分配前引用的局部变量“链接”
【发布时间】:2018-02-22 05:10:43
【问题描述】:

我实现的 Scrapy 解析方法给了我错误:

UnboundLocalError: 赋值前引用了局部变量“链接”

对scrapy来说还很陌生,我对我在这里做错了什么知之甚少。我想为将来添加的新网站留出空间,但是如何实现该网站特有的 xpath 以便它抓取其内部链接?

xpath 是正确的并且可以在 shell 中工作。

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from rvcalinkscrapper.items import RvcalinkscrapperItem
from scrapy.loader import ItemLoader
from scrapy.loader.processors import TakeFirst, MapCompose
from w3lib.html import remove_tags

class MultifileoutSpider(scrapy.Spider):
name = 'multifileout'
allowed_domains = []
start_urls = []
read_urls = open('../urls.txt', 'r')
for url in read_urls.readlines():
    url = url.strip() 
    allowed_domains = allowed_domains + [url[4:]]
    start_urls = start_urls + ['http://' + url]
read_urls.close()

def parse(self, response):

    item_loader = ItemLoader(item=RvcalinkscrapperItem(), response=response)
    item_loader.default_input_processor = MapCompose(remove_tags)
    item_loader.default_output_processor = TakeFirst()

    shop = response.xpath("shop")
    if shop == "shop0":
        links = '//li[@class="mobile-nav__item"]/a/@href'
    elif shop == "shop1":
        links = '//ul[@class="level2 unstyled"]/li/a/@href'

    item_loader.add_xpath("links", links)

    item_loader.add_value("shop", shop)

    item_loader.add_value("url", response.url)

    return item_loader.load_item()

【问题讨论】:

  • 如果shop 既不是"shop0" 也不是"shop1",则变量links 未初始化。无论哪种情况,您都应该给它一个默认值或不使用它。
  • @DyZ 你能用一个有效的代码补丁来回答吗?
  • 但是看看下面@BruceWayne 的回答。

标签: python


【解决方案1】:

如果shop 不是这两件事之一,则不会分配links。你可以这样做

...
links = '//li[@class="mobile-nav__item"]/a/@href'
shop = response.xpath("shop")
if shop == "shop1":
    links = '//ul[@class="level2 unstyled"]/li/a/@href'
...

假设您要使用“默认”路径(我使用了shop0's)。显然你可以切换它,或者添加一个elif

【讨论】:

  • 同样的错误仍然存​​在。这就是我所做的。 shop = response.xpath("shop") if shop == "shop0": links = '//li[@class="mobile-nav__item"]/a/@href' shop = response.xpath("shop") if shop == "shop1": links = '//ul[@class="level2 unstyled"]/li/a/@href' item_loader.add_xpath("links", links)
  • @anshumananand - 你肯定shop = ... 只会返回shop1shop0?不是,比如shop3no1 等等?
  • 当添加新网站时,我肯定需要使用 shop3 再添加一个 xpath,因此它也必须返回 shop3。
  • @anshumananand 但目前您确定links 将成为这两条路径之一吗?如果不是不是,你想为links返回什么?
猜你喜欢
  • 1970-01-01
  • 2020-07-08
  • 1970-01-01
  • 2017-08-10
  • 2020-01-16
  • 2019-12-05
  • 2017-09-19
  • 2020-09-26
  • 2022-01-02
相关资源
最近更新 更多