2014-02-14 46 views
0

嘗試使用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)

回答

2

回溯指示Beau tifulSoup或Python安裝正在抱怨。看看their documentation

If you're getting errors that say: "'ascii' codec can't encode character 'x' in position y: ordinal not in range(128)", the problem is probably with your Python installation rather than with Beautiful Soup. Try printing out the non-ASCII characters without running them through Beautiful Soup and you should have the same problem. For instance, try running these three lines of code like this:

>>> 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") 
+0

我加入了kwarg但由於某種原因它仍然給了我同樣的錯誤。 – Thomas

+0

哎呦,我誤讀了回溯。嘗試'latin1word ='Sacr \ xe9 bleu!'unicodeword = unicode(latin1word,'latin-1')''在你的解釋器中打印unicodeword''。如果這給了你另一個'UnicodeError',問題出在你的Python安裝上。如果這很好,那麼在安裝BeautifulSoup時會出現問題。我可以問你爲什麼在BS3而不是BS4上? – pswaminathan

+0

如果你的Python安裝也打印了正確的unicode字符,那麼問題出現在BeautifulSoup上;你應該升級到BS4。雖然您可能無法按照T所看到的教程進行操作,但仍然可以使用相同的基本模式。 – pswaminathan

0

之所以能夠加入.encode(「utf-8」)來做到這一點。

例如

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))