【问题标题】:Basic fetching of a URL's HTML body with Python 3.x使用 Python 3.x 基本获取 URL 的 HTML 正文
【发布时间】: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;'

【问题讨论】:

    标签: python url urllib2


    【解决方案1】:

    GIF89a 表示服务器正在向您发送图像。

    另外,无论如何,您不应该使用 UTF-8 进行暴力解码;您应该查看响应标头以确定要使用的编码。

    【讨论】:

    • Content-Type头获取字符编码:response.info().get_param('charset')
    猜你喜欢
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多