UnboundLocalError:局部变量'items'在赋值前被引用

0 投票
3 回答
11621 浏览
提问于 2025-04-17 12:01

可能重复的问题:
将列表转换为字符串,以便在Python Scrapy中插入到MySQL的一行中

我正在尝试将从HTML页面提取的数据直接写入MySQL数据库。但是,之前能正常工作的代码现在不再有效了。有人能帮我解决这个问题吗?

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    sites = hxs.select('//ul/li')
    con = MySQLdb.connect(
        host="localhost",
        user="dreamriks",
        passwd="dreamriks",
        db="scraped_data"
    )
    cur = con.cursor()
    for site in sites:
        items = [site.select('//h2').extract()]
        item = [site.select('//h3').extract()]
        meta = [site.select('//meta').extract()]
    for index in range (len( items)):              #<-- exception raises here
        str = items[index]
        cur.execute("""Insert into h2_meta(h2) Values(%s)""",(str))
    con.commit()
    con.close()

上面的代码出现了以下错误:

exceptions.UnboundLocalError: local variable 'items' referenced before assignment

3 个回答

0

如果 for site in sites: 这个循环没有执行,因为 sites 是空的,那么 items 就不会被初始化。

当你在 for index in range(len(items)): 这行代码中使用它时,代码假设 items 已经被初始化了。

2

看起来你有个缩进的问题。for index in range(len(items))for site in sites 循环的一部分,对吧?

    for site in sites:
        items = [site.select('//h2').extract()]
        item = [site.select('//h3').extract()]
        meta = [site.select('//meta').extract()]
        for index in range (len( items)):             # <-- make sure this has same
             str = items[index]                       # level of indenting as previous lines
             cur.execute("""Insert into h2_meta(h2) Values(%s)""",(str))
2

你的缩进有问题。请调整一下这个代码块的缩进。

for index in range (len( items)):
    str = items[index]
    cur.execute("""Insert into h2_meta(h2) Values(%s)""",(str))

再多加四个空格。

撰写回答