【发布时间】:2011-08-08 11:07:21
【问题描述】:
我是 Python 新手。我对 Python 2.x 中的旧 urllib 和 urllib2 与 Python 3 中的新 urllib 之间的差异感到有些困惑,除此之外,我不确定何时需要对数据进行编码,然后才能发送到 urlopen。
我一直在尝试使用 POST 获取 url 的 html 正文,以便我可以发送参数。该网页显示一个国家在给定一天的特定小时内的日照数据。我试过不编码/解码,打印输出是一串以 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;'
【问题讨论】: