UnboundLocalError:赋值前引用了局部变量“items" [英] UnboundLocalError: local variable 'items' referenced before assignment

查看:29
本文介绍了UnboundLocalError:赋值前引用了局部变量“items"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
转换列表将字符串插入到我的 sql 中,在 python scrapy 中的一行

我正在尝试将从 HTML 页面中提取的数据直接写入 MySQL 数据库.但是,曾经有效的代码不再有效.有人可以帮我吗?

I am trying to write the data extracted from HTML pages directly to a MySQL database. But the code, which used to work, no longer does. Can someone please help me out?

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()

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

The code above gives the following error:

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

推荐答案

您似乎遇到了缩进问题.for index in range(len(items))for site in sites 循环的一部分,对吗?

It looks like you have an indenting problem. The for index in range(len(items)) is part of the for site in sites loop, right?

    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))

这篇关于UnboundLocalError:赋值前引用了局部变量“items"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆