现在的情况是,我发送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®=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)
每当我尝试更改响应头内容类型:text/html;charset=utf-8时,我都会
response['Content-Type'] = 'text/html;charset=utf-8'
我得到这个错误:
AttributeError: addinfourl instance has no attribute '__setitem__'
我的问题:是否可以编辑或删除响应或请求头? 如果没有,除了将源代码复制到notepad++并手动修复编码之外,是否还有其他方法可以解决此问题?
我对python和数据挖掘还不熟悉,真希望你能告诉我,如果我做错了什么
谢谢
为什么不尝试
thepage = the_page.decode('utf-8')
而不是encode
,因为您想要的是从utf-8编码的文本移动到unicode编码的不可知的内部字符串?两件事。首先,您不想对响应进行编码,而是要对其进行解码:
其次,您不想在响应上设置头,而是在请求上设置头,使用
add_header
方法:相关问题 更多 >
编程相关推荐