我是一个Python新手。我对Python 2.x中旧版urllib和urllib2与Python 3中新版urllib之间的差异有些困惑,而且还不确定在发送到urlopen之前何时需要对数据进行编码。
我一直在尝试获取网址的HTML正文,使用POST发送参数。该网页显示了一个国家在给定日期的特定小时内的阳光数据。我已经尝试过不进行编码/解码,输出结果是以b开头的字节字符串。然后我尝试的代码是:
import urllib.request, urllib.parse, urllib.error
def scrape(someurl):
try:
values = {'LANG': 'en',
'DATE' : '1303160400',
'CONT' : 'euro',
'LAND' : 'UK',
'KEY' : 'UK',
'SORT': '2',
'INT' : '06',
'TYPE' : 'sonnestd',
'ART' : 'karte',
'RUBRIK' : 'akt',
'R': '310',
'CEL': 'C'}
data = urllib.parse.urlencode(values)
data = data.encode("utf-8")
response = urllib.request.urlopen(someurl, data)
html = response.read().decode("utf-8")
print(html)
except urllib.error.HTTPError as e:
print(e.code)
print(e.read())
myscrape = scrape("http://www.weatheronline.co.uk/weather/maps/current")
错误信息为:
Traceback (most recent call last):
File "/Users/Me/Desktop/weather.py", line 57, in <module>
myscrape = scrape("http://www.weatheronline.co.uk/weather/maps/current")
File "/Users/Me/Desktop/weather.py", line 37, in scrape
html = response.read().decode("utf-8")
UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 10: invalid start byte
没有进行编码/解码,我得到的字节串非常短,因此我想知道是否请求以某种其他方式失败了。
b'GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;'
Content-Type
头中获取字符编码:response.info().get_param('charset')
- jfs