嘗試使用python將刮掉的天氣數據保存到mysql數據庫中,但由於度符號而給出了錯誤,任何人都知道如何讓它工作?python scraper不能保存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:/用戶/所有者/ PycharmProjects/WeatherStation/Innovation Scraper.py「,第18行,在 results =(str(tds [2] .text),str(tds [3] .text),str(tds [6] .span.text ), UnicodeEncodeError:'ascii'編碼解碼器無法在位置1編碼字符u'\ xb0':序號不在範圍內(128)
我加入了kwarg但由於某種原因它仍然給了我同樣的錯誤。 – Thomas
哎呦,我誤讀了回溯。嘗試'latin1word ='Sacr \ xe9 bleu!'unicodeword = unicode(latin1word,'latin-1')''在你的解釋器中打印unicodeword''。如果這給了你另一個'UnicodeError',問題出在你的Python安裝上。如果這很好,那麼在安裝BeautifulSoup時會出現問題。我可以問你爲什麼在BS3而不是BS4上? – pswaminathan
如果你的Python安裝也打印了正確的unicode字符,那麼問題出現在BeautifulSoup上;你應該升級到BS4。雖然您可能無法按照T所看到的教程進行操作,但仍然可以使用相同的基本模式。 – pswaminathan