简体   繁体   English

将列表转换为字符串以在python scrapy中的一行中插入我的sql

[英]convert list to string to insert into my sql in one row in python scrapy

I want to convert a list object into a string and insert this string as one row in mysql database. 我想将列表对象转换为字符串并将此字符串作为一行插入mysql数据库中。 Can someone please provide a solution to this. 有人可以提供解决方案吗? My code looks like this: 我的代码如下所示:

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    sites = hxs.select('//ul/li')
    for site in sites:
         con = mysqldb.connect(
                    host="localhost",
                    user="dreamriks",
                    passwd="dreamriks",
                    db="scraped_data"
                 )
         cur = con.cursor()
         quest = site.select('//h2').extract()
         ans = site.select('//h3').extract()
         meta = site.select('//meta').extract()
         cur.execute("""Insert into scraped_data(h2, h3, meta) Values(%s,%s,%s)""",(quest,ans,meta))                   
         con.commit()
         con.close()

The code above gives the following error: 上面的代码给出以下错误:

File "/usr/local/lib/python2.7/dist-packages/Scrapy-0.14.0.2841-py2.7.egg/scrapy/spider.py", line 62, in parse
        raise NotImplementedError
    exceptions.NotImplementedError:

Can someone help me with this error. 有人可以帮我解决这个错误。 I am stuck at this. 我被困在这里。

l = ['foo', 'bar', 'baz']
ls = ", ".join(l)
# ls == "foo, bar, baz"

Now you can insert this string into your database. 现在,您可以将此字符串插入数据库。

Not sure where your list is in the sample code, but you create a string from a list using join : 不确定列表在示例代码中的位置,但是您可以使用join从列表中创建一个字符串:

l = ['The','quick','brown','fox']
s = ''.join(l)
print(s)

gives: 给出:

Thequickbrownfox

If you want to convert a list into a string you can use join . 如果要将list转换为string ,可以使用join

>>> myl = ['a','b','c']
>>> "".join(myl)
'abc'

you can use any delimiter of your choice in between the quotes 您可以在引号之间使用您选择的任何定界符

>>> myl = ['a','b','c']
>>> ",".join(myl)
'a,b,c'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM