2012-02-27 144 views
1

的情況,我送POST請求,並試圖獲取與Python的響應 問題是,它扭曲了非拉丁字母,當我取得與直接鏈接在同一頁不發生(沒有搜索結果),但POST請求不會生成鏈路的Python POST請求編碼

這裏是我做的:

import urllib 
import urllib2 
url = 'http://donelaitis.vdu.lt/main_helper.php?id=4&nr=1_2_11' 
data = 'q=bus&ieskoti=true&lang1=en&lang2=en+-%3E+lt+%28+71813+lygiagre%C4%8Di%C5%B3+sakini%C5%B3+%29&lentele=vertikalus&reg=false&rodyti=dalis&rusiuoti=freq' 
req = urllib2.Request(url, data) 
response = urllib2.urlopen(req) 
the_page = response.read() 
file = open("pagesource.txt", "w") 
file.write(the_page) 
file.close() 

每當我試圖

thepage = the_page.encode('utf-8') 

我得到這個錯誤:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 1008: ordinal not in range(128) 

每當我試圖做變化的響應報頭的Content-Type:text/html的;字符集= UTF-8,我做

response['Content-Type'] = 'text/html;charset=utf-8' 

我得到這個錯誤:

AttributeError: addinfourl instance has no attribute '__setitem__' 

我的問題:是否可以編輯或刪除響應或請求標題? 如果沒有,是否有另一種方法來解決這個問題,其他複製源到記事本++和手動固定編碼?

我是新來的Python和數據挖掘,真希望你讓我知道如果我; M做錯事

感謝

回答

1

兩件事情。首先,你不想編碼的響應,你要對它進行解碼:

thepage = the_page.decode('utf-8') 

其次,你不想設置頁眉上的反應,將其設置上的要求,使用add_header方法:

req.add_header('Content-Type', 'text/html;charset=utf-8') 
+0

當我向請求添加標題時,它返回沒有搜索結果的頁面。 我想改變響應頭文本/ html;字符集= UTF-8「到 'text/html的',bacause附加字符集= UTF-8可能是造成問題的原因,沒有? – Earl 2012-02-27 11:38:03

+1

這可能意味着更改您已閱讀的回覆的標題?我根本不懂。 – 2012-02-27 11:53:41

+0

嗯,我的意思是莫名其妙地檢索如果沒有編碼線的響應...不知道壽,如果能夠幫助或者是技術上posibble在所有 – Earl 2012-02-27 12:03:53

2

爲什麼不試試你的thepage = the_page.decode('utf-8')代替encode因爲你要的是從UTF-8編碼的文本爲Unicode移動 - 編碼無關 - 內部字符串?

+0

我試圖解碼(「UTF-8」),以及,我得到這個錯誤: UnicodeDecodeError:'utf8'無法解碼位置7281-7282中的字節:無效的連續字節 – Earl 2012-02-27 11:33:18