python - 插入 MySQL 时出错

标签 python mysql html database django

_mysql_exceptions.Warning: Incorrect string value: '\xE7\xB9\x81\xE9\xAB\x94...' for column 'html' at row 1


def getSource(theurl, moved = 0):
    if moved == 1:
        theurl = urllib2.urlopen(theurl).geturl()
    urlReq = urllib2.Request(theurl)
    urlReq.add_header('User-Agent',random.choice(agents))
    urlResponse = urllib2.urlopen(urlReq)
    htmlSource = urlResponse.read()
    return htmlSource

new_u = Url(source_url = source_url, source_url_short = source_url_short, source_url_hash = source_url_hash, html = htmlSource)
new_u.save()

为什么会这样? 我主要是下载页面的 URL...然后使用 Django 将其保存到数据库。

它只是有时会发生......有时它工作正常。

编辑:我好像必须将数据库设置为 UTF-8?这样做的命令是什么?

最佳答案

您基本上需要确保正确的字符串编码。例如。您提供给 django 的字符串不是 UTF-8 编码的,因此无法解析某些字符。

有关如何查找所请求页面的编码的一些有用建议可在此处找到:urllib2 read to Unicode

关于python - 插入 MySQL 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1808455/

相关文章:

javascript - li 元素内的作用域函数未被调用

python - 在 python 中编写 "try elsetry"的最佳方法?

python - numpy.piecewise 中的多个部分

php - 在 php mysql 中使用 if 条件未获取查询输出

带枚举的 mysql 查询

html - 将文件包含在另一个文件中时,图像路径未引用根文件夹

html - 在一个序列中放置两个元素

python - 如何使用python多字典中的键获取值

python - 绘制三元/三角图的库/工具

mysql - WHERE语句一侧的SQL Lower()对部分结果有效,但不是全部?