【发布时间】:2012-01-31 12:33:37
【问题描述】:
可能重复:
convert list to string to insert into my sql in one row in python scrapy
我正在尝试将从 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
【问题讨论】:
-
你需要用更合适的标题提出更好的问题。这个问题对其他人几乎没有任何价值,即使有,人们如何搜索它?此外,审查用户名和密码可能是个好主意。
标签: python variable-assignment