我遇到了这个错误:UnicodeEncodeError: 'latin-1'编解码器无法编码字符u'\u2014'
我正在尝试将许多新闻文章加载到MySQLdb中。然而,我很难处理非标准字符,我会因为各种字符而出现数百个这样的错误。我可以使用.replace()逐个处理它们,但我希望有一个更完整的解决方案来正确地处理它们。
ubuntu@ip-10-0-0-21:~/scripts/work$ python test_db_load_error.py
Traceback (most recent call last):
File "test_db_load_error.py", line 27, in <module>
cursor.execute(sql_load)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 157, in execute
query = query.encode(charset)
UnicodeEncodeError: 'latin-1' codec can't encode character u'\u2014' in position 158: ordinal not in range(256)
我的脚本;
import MySQLdb as mdb
from goose import Goose
import string
import datetime
host = 'rds.amazonaws.com'
user = 'news'
password = 'xxxxxxx'
db_name = 'news_reader'
conn = mdb.connect(host, user, password, db_name)
url = 'http://www.dailymail.co.uk/wires/ap/article-3060183/Andrew-Lesnie-Lord-Rings-cinematographer-dies.html?ITO=1490&ns_mchannel=rss&ns_campaign=1490'
g = Goose()
article = g.extract(url=url)
body = article.cleaned_text
body = body.replace("'","`")
load_date = str(datetime.datetime.now())
summary = article.meta_description
title = article.title
image = article.top_image
sql_load = "insert into articles " \
" (title,summary,article,,image,source,load_date) " \
" values ('%s','%s','%s','%s','%s','%s');" % \
(title,summary,body,image,url,load_date)
cursor = conn.cursor()
cursor.execute(sql_load)
#conn.commit()
非常感谢您的帮助。
sql_load
行中删除% (....)
,并将元组移动到cursor.execute()
的第二个参数中。sql_load =“....带有%s占位符的查询字符串...”
和cursor.execute(sql_load,(title,summary,body,image,url,load_date))
。 - Martijn Pieters