_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/