当我想将Python
代码中的字符串插入SQLite
数据库时,我收到此错误:
sqlite3.ProgrammingError:除非使用8位字节串,否则不得使用 你使用一个可以解释8位字节串的text_factory(比如 text_factory = str)。强烈建议您改为 将您的应用程序切换到Unicode字符串。
这是插入声明:
cur.execute("insert into links (url, title, ...) values (:url, :title, ...)", locals())
该字符串的存在如下:
soup = BeautifulSoup(html.read(), fromEncoding="utf-8")
html.close()
for i in soup.findAll('a'):
url = i['href']
title = i.renderContents()
您能否告诉我如何将字符串插入SQLite database
?
编辑:我发现插入到另一个表时url
字符串是可以的。 url
字符串的类型为unicode
。问题是插入title
字符串时。 title
字符串的类型为str
。
我试过了:
title = unicode(i.renderContents())
但这以错误结束:
UnicodeDecodeError:'ascii'编解码器无法将字节0xc3解码到位 44:序数不在范围内(128)
谢谢
答案 0 :(得分:3)
SQLite只存储unicode字符串。很可能是不是unicode的URL,所以你需要转换它。
您可以将URL存储为blob(二进制),但这会使以后的生活更加复杂。
答案 1 :(得分:1)
虽然对于网址并不是绝对必要的,但您可以将其存储为Unicode。
BeautifulSoup
适用于Unicode。
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("""<a href="ascii">""", fromEncoding="utf-8")
>>> isinstance(soup('a', href=True)[0]['href'], unicode)
True
>>> soup = BeautifulSoup("""<a href="αβγ">""", fromEncoding="utf-8")
>>> soup('a', href=True)[0]['href']
u'\u03b1\u03b2\u03b3'
在这两种情况下,网址都是unicode
。
您可以致电isinstance()
或type()
,了解网址的类型。
您可以指定encoding=None
来获取Unicode:
i.renderContents(encoding=None)
通常,在交互式Python控制台中使用dir(obj)
,help(obj.method)
可能会有所帮助。另请参阅Printing Document。