问题
Possible Duplicate:
convert list to string to insert into my sql in one row in python scrapy
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
回答1:
Your indention is broken. Indent the block
for index in range (len( items)):
str = items[index]
cur.execute("""Insert into h2_meta(h2) Values(%s)""",(str))
four more spaces.
回答2:
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))
回答3:
If for site in sites:
doesn't iterate because sites
is empty, then items
never gets initialised.
When you reference it in for index in range (len( items)):
the code is assuming that items
has been intialised.
来源:https://stackoverflow.com/questions/9079560/unboundlocalerror-local-variable-items-referenced-before-assignment