error while inserting into mysql from python for loop [duplicate]

2024/10/11 11:17:46

Possible Duplicate:
convert list to string to insert into my sql in one row in python scrapy

Is this script correct. I want to insert the scraped out h2,h3,meta data directly into mysql database. The code below does not work correctly. Can someone please provide a solution to this. I think the problem is with the for loop.

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

The error that comes is:

 for index,index1,index2 in range (len( items)),range(len(item)),range(len(item1)):exceptions.ValueError: need more than 1 value to unpack
Answer

It seems one of your list has only one element in them, which is causing the problem. Please check all the lists :

 items = [site.select('//h2').extract()]item = [site.select('//h3').extract()]item1 = [site.select('//meta').extract()]

Make sure they are as expected.

for index,index1,index2 in range (len( items)),range(len(item)),range(len(item1))

this syntax iterates over all the lists at once, if any of the len of lists don't match, value error will be raised,

For Better understanding of your problem see below:

In [1]: l1 = [1,2,3]In [2]: l2 = [4,5,6]In [3]: l3 = [7]In [4]: for index,index1,index2 in range (len( l1)),range(len(l2)),range(len(l3)):....:     print "Hi"....:     ....:     
Hi
Hi
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)/home/avasal/<ipython console> in <module>()ValueError: need more than 1 value to unpack

can you try this if possible:

for index,index1,index2 in zip(range (len( items)),range(len(item)),range(len(item1)))
https://en.xdnf.cn/q/118331.html

Related Q&A

Half of Matrix Size Missing

I wanted to ask why is it that some of my matrices in Python are missing a size value? The matrices/arrays that re defined show the numbers in them, but the size is missing and it is throwing me other…

Clicking Side Panel Elements in Selenium Without IFrames

I want to download U.S. Department of Housing and Urban Development data using Pythons Selenium. Heres my code. import os from selenium import webdriver from webdriver_manager.chrome import ChromeDrive…

Library to extract data from open Excel workbooks

I am trying to extract data from workbooks that are already open. I have found the xlrd library, but it appears you can only use this with workbooks you open through Python. The workbooks I will use in…

Keras apply different Dense layer to each timestep

I have training data in the shape of (-1, 10) and I want to apply a different Dense layer to each timestep. Currently, I tried to achieve this by reshaping input to (-1, 20, 1) and then using a TimeDis…

Create a pass-through for an installed module to achieve an optional import

Im writing a library in python 3.7. Id like it to have as few dependencies as possible. For example, tqdm is nice to have but ideally Id like my library to work without it if its not there. Therefore, …

Django, Redis: Where to put connection-code

I have to query redis on every request in my Django-app. Where can I put the setup/ connection routine (r = redis.Redis(host=localhost, port=6379)) so that I can access and reuse the connection without…

Events and Bindings in tkinter does not work in loop

I am trying to create binding in a loop using tkinter module.from tkinter import * class Gui(Frame):def __init__(self, parent):Frame.__init__(self, parent) self.parent = parentself.initUI()def Arrays(…

Python Machine Learning Algorithm to Recognize Known Events

I have two sets of data. These data are logged voltages of two points A and B in a circuit. Voltage A is the main component of the circuit, and B is a sub-circuit. Every positive voltage in B is (1) co…

How can I replace Unicode characters in Python?

Im pulling Twitter data via their API and one of the tweets has a special character (the right apostrophe) and I keep getting an error saying that Python cant map or character map the character. Ive lo…

Filtering Pandas DataFrame using a condition on column values that are numpy arrays

I have a Pandas DataFrame called dt, which has two columns called A and B. The values of column B are numpy arrays; Something like this: index A B 0 a [1,2,3] 1 b [2,3,4] 2 c …