標籤:
從網站上擷取的資訊要儲存在本地
資料庫中,但是儲存的過程中資料庫的資訊都變成了亂碼,怎麼解決呢?客官聽我娓娓道來。 首先,保證以下四項的編碼都是utf-8: 1. 代碼 2. 資料庫連接 3. 表的字元集格式 4. 插入的資料格式 每步的操作如下: 1. 保證代碼的格式是utf-8,在代碼最前面加上這句話 # -*- coding:utf8 -*- #首先用於確定編碼,加上這句 2. 保證資料庫連接格式是utf-8,這麼寫 conn=MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘****‘,db=‘kfxx‘,port=3306,charset=‘utf8‘) cur=conn.cursor() 3. 保證表的字元集格式是utf-8,在建表的時候就能設定 4. 保證插入的資料格式是utf-8,分為保證讀取的頁面格式是utf-8和字串格式也是utf-8 #解決亂碼問題
| html_1 = urllib2.urlopen(cityURL,timeout=120).read()mychar = chardet.detect(html_1)bianma = mychar[‘encoding‘]if bianma == ‘utf-8‘ or bianma == ‘UTF-8‘:html = html_1else :html = html_1.decode(‘gb2312‘,‘ignore‘).encode(‘utf-8‘) |
| chapter_soup = BeautifulSoup(html)city = chapter_soup.find(‘div‘,class_ = ‘row-fluid‘).find(‘h1‘).get_text()province = chapter_soup.find(‘a‘,class_ = ‘province‘).get_text()pmNum = chapter_soup.find(‘div‘,class_ = ‘row-fluid‘).find(‘span‘).get_text()suggest = chapter_soup.find(‘div‘,class_ = ‘row-fluid‘).find(‘h2‘).get_text()rand = chapter_soup.find(‘div‘,class_ = ‘row-fluid‘).find(‘h2‘).find_next_sibling(‘h2‘).get_text()face = chapter_soup.find(‘div‘,class_ = ‘span4 pmemoji‘).find(‘h1‘).get_text()conclusion = chapter_soup.find(‘h1‘,class_ = ‘review‘).get_text()print city.encode(‘utf-8‘)cur.execute(‘insert into t_pm values(\‘‘+city.encode(‘utf-8‘)+‘\‘,\‘‘+province.encode(‘utf-8‘)+‘\‘,\‘‘+pmNum.encode(‘utf-8‘)+‘\‘,\‘‘+suggest.encode(‘utf-8‘)+‘\‘,\‘‘+rand.encode(‘utf-8‘)+‘\‘,\‘‘+conclusion.encode(‘utf-8‘)+‘\‘)‘) |
完成,插入的資料都是中文了,看:
解決資料庫插入之後的亂碼問題 【轉】