2017-07-06 39 views
0

我有以下問題:是否有一個網站編碼在windows-1251。我正在使用BeautifulSoup庫來獲取俄語所需的數據。爲了測試記錄文件中的值,它們顯示正確。然後我試圖將這些數據記錄到數據庫中,但得到這個錯誤:Warning: (1366, "Incorrect string value: '\\x98\\xD0\\xBD\\xD1\\x82\\xD0...' for column 'description' at row 1") 數據庫編碼是utf-8。 下面的代碼演示瞭如何讀取HTML文件:pymysql不正確的寫入數據庫的俄文文本

def get_html(url): 
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) 
response = urllib.request.urlopen(req) 
return response.read() 

下面的代碼演示瞭如何將值寫入到數據庫:

def write_to_db(chars, desc): 
    conn = pymysql.connect(host='localhost', 
     port=3307, 
     user='****', 
     password='****', 
     db='****', 
     charset='utf8', 
     cursorclass=pymysql.cursors.DictCursor) 

global _id 
with conn.cursor() as cursor: 
    sql = "INSERT INTO `articles` (`id_cat`, `characteristics`, `description`) VALUES (%s, %s, %s)" 
    cursor.execute(sql, (_id, chars, desc)) 
conn.commit() 

在我們的數據庫中獲取以下字符結尾:Модель

我該如何克服這個問題?

回答

0

當我嘗試將整個html文件的編碼更改爲utf8時,出現一些字符無法解碼的錯誤。並在下面呈現的方式,我們已經收到俄文本沒有不必要的符號,可以從容地將其解碼

with conn.cursor() as cursor: 
    sql = "INSERT INTO `articles` (`id_cat`, `characteristics`, `description`) VALUES (%s, %s, %s)" 
    cursor.execute(sql, (_id, chars.encode('utf8'), desc.encode('utf8'))) 
conn.commit() 
+0

解釋爲什麼這樣做會幫助所有人 – jwenting

0

嘗試改變數據庫編碼cp1251_general_ci。

this link您可以檢查西里爾文字符集和歸類。