我正在使用Beautifulsoup从中文网站上抓取中文文本,并尝试通过Python中的MySQLdb将我抓取的字符串插入到mysql数据库中。但是我在执行查询时遇到了UnicodeEncodeError。代码如下:
movie_name_fail = my_beautifulsoup_object.find("div").text
my_cursor.execute("INSERT INTO MOVIE_TABLE VALUES(%s)",movie_name_fail)
它给了我错误:
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-7: ordinal not in range(256)
但是当我这样做时
print movie_name_fail
可以正确打印汉字。 而且我已经声明了
#!/usr/bin/python
# -*- coding: utf-8 -*-
作为我的python源文件的编码,但它不起作用。然而,当我直接在文本编辑器中输入相同的汉字时(我使用的是 sublime text),它工作得很好,我能够将它插入到 mysql 中并正确显示在 mysql 控制台中(我已经将mysql中表的字符集设置为utf8):
movie_name_success = "超人总动员"
my_cursor.execute("INSERT INTO MOVIE_TABLE VALUES(%s)",movie_name_success)
我无法弄清楚该错误为何发生以及它是如何工作的。我真的很感激任何帮助。
更新
我的python版本是2.7.8,MYSQL版本是5.7.11
我将源代码推送到 github,它应该能够重现第 117 行的错误:“db_cursor.executemany(insert_sql,movie_tuple_list)”
https://github.com/shawnli2010/JHSaver/blob/master/LeTV_scraper.py
最佳答案
Python 构造在进行替换时是否添加引号?它需要。
您是否建立了 utf8mb4 连接?
表/列是字符集utf8mb4
吗?
我建议使用utf8mb4而不是utf8,因为中文有一些字符需要4个字节。
关于python - python向mysql插入中文字符时出现UnicodeEncodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36635495/