尝试使用python将刮刮的天气数据保存到mysql数据库中,但由于度数符号而给出错误,任何人都知道如何使其工作?
我的代码是;
import urllib2
import MySQLdb
from BeautifulSoup import BeautifulSoup
db = MySQLdb.connect("127.0.0.1","root","","weathersystem")
cursor = db.cursor()
sql = "TRUNCATE TABLE AMSTERDAM "
cursor.execute(sql)
db.commit()
db.close
soup = BeautifulSoup(urllib2.urlopen('http://weather.uk.msn.com/tenday.aspx? wealocations=wc:NLXX0002').read())
for row in soup('div', {'class': 'weadetailed'})[0]('li'):
tds = row('div')
print tds[2].text, tds[3].text, (tds[6].span.text), tds[7].span.text, tds[8].text, tds[9].text
cursor = db.cursor()
sql = "INSERT INTO AMSTERDAM(DAY, DATE, HIGH, LOW, WIND, HUMIDITY) VALUES (%s,%s,%s,%s,%s,%s)"
results = (str(tds[2].text), str(tds[3].text), str(tds[6].span.text),
str(tds[7].span.text), str(tds[8].text), str(tds[9].text))
cursor.execute(sql, results)
db.commit()
db.rollback()
db.close()
然后我收到了这个错误,
追踪(最近一次通话): 今天2月14日9°5°风18英里/小时SW湿度74% 文件“C:/ Users / owner / PycharmProjects / WeatherStation / Innovation Scraper.py”,第18行,in results =(str(tds [2] .text),str(tds [3] .text),str(tds [6] .span.text), UnicodeEncodeError:'ascii'编解码器无法对位置1中的字符u'\ xb0'进行编码:序数不在范围内(128)
答案 0 :(得分:2)
回溯表明BeautifulSoup或Python安装正在抱怨。看看their documentation:
如果您收到错误,说:“'ascii'编解码器无法编码位置y中的字符'x':序号不在范围内(128)”,问题可能在于您的Python安装而不是美丽汤。尝试打印非ASCII字符而不通过Beautiful Soup运行它们,你应该遇到同样的问题。例如,尝试运行这三行代码:
>>> latin1word = 'Sacr\xe9 bleu!'
>>> unicodeword = unicode(latin1word, 'latin-1')
>>> print unicodeword
Sacré bleu!
(请注意,这应该在交互式解释器中,而不是在脚本中。在脚本中,如果你把它放在底部,你仍然会收到错误。)
如果可行(即你看到最后一行返回),问题在于BeautifulSoup,是的,你应该升级到bs4。如果该打印行吐出回溯,则问题在于安装Python。可以在上面的链接中找到解决它的说明。
另一方面,MySQLdb默认使用latin1字符集。除非您包含kwarg charset='utf8'
,否则您将无法将该Unicode数据插入表中:
db = MySQLdb.connect("127.0.0.1","root","","weathersystem", charset="utf8")
答案 1 :(得分:0)
能够通过添加.encode('utf8')来实现。
例如
results = (str(tds[2].text), str(tds[3].text), str(tds[6].span.text.encode('utf8')),
str(tds[7].span.text.encode('utf8')), str(tds[8].text), str(tds[9].text))