UnboundLocalError:赋值前引用了局部变量“items"

编程入门 行业动态 更新时间:2024-10-27 09:35:35
本文介绍了UnboundLocalError:赋值前引用了局部变量“items"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

可能的重复:
转换列表将字符串插入到我的 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))
    conmit()
    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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-28 07:15:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1169738.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:赋值   变量   局部   UnboundLocalError   items

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!