Python3:使用 urllib 时出现 HTTP 错误 302 [英] Python3: HTTP Error 302 while using urllib

查看:42
本文介绍了Python3:使用 urllib 时出现 HTTP 错误 302的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从网站上读取不同股票的价值.因此我写了这个小脚本,它读取页面源代码,然后解析出值:

I want to read the value of different stocks from websites. Therefore I wrote this tiny script, which reads the page source and then parses out the value:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from re import search
from urllib import request


def main():
    links = [
        [
            'CSG',
            'UBS',
        ],
        [
            'http://www.tradegate.de/orderbuch.php?isin=CH0012138530',
            'http://www.tradegate.de/orderbuch.php?isin=CH0244767585',
        ],
    ]

    for i in in range(len(links[0])):
        url = links[1][i]
        htmltext = request.urlopen(url).read().decode('utf-8')
        source = htmltext.splitlines()
        for line in source:
            if 'id="bid"' in line:
                m = search('\d+.\d+', line)
                print('{}'.format(m.string[m.start():m.end()]))


if __name__ == '__main__':
    main()

有时它有效,但有时会引发此错误:

sometimes it works but sometimes this error gets raised:

Traceback (most recent call last):
  File "./aktien_reader.py", line 39, in <module>
    main()
  File "./aktien_reader.py", line 30, in main
    htmltext = request.urlopen(url).read().decode('utf-8')
  File "/usr/lib/python3.3/urllib/request.py", line 160, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.3/urllib/request.py", line 479, in open
    response = meth(req, response)
  File "/usr/lib/python3.3/urllib/request.py", line 591, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python3.3/urllib/request.py", line 511, in error
    result = self._call_chain(*args)
  File "/usr/lib/python3.3/urllib/request.py", line 451, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.3/urllib/request.py", line 696, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/usr/lib/python3.3/urllib/request.py", line 479, in open
    response = meth(req, response)
  File "/usr/lib/python3.3/urllib/request.py", line 591, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python3.3/urllib/request.py", line 511, in error
    result = self._call_chain(*args)
  File "/usr/lib/python3.3/urllib/request.py", line 451, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.3/urllib/request.py", line 696, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/usr/lib/python3.3/urllib/request.py", line 479, in open
    response = meth(req, response)
  File "/usr/lib/python3.3/urllib/request.py", line 591, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python3.3/urllib/request.py", line 511, in error
    result = self._call_chain(*args)
  File "/usr/lib/python3.3/urllib/request.py", line 451, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.3/urllib/request.py", line 696, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/usr/lib/python3.3/urllib/request.py", line 479, in open
    response = meth(req, response)
  File "/usr/lib/python3.3/urllib/request.py", line 591, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python3.3/urllib/request.py", line 511, in error
    result = self._call_chain(*args)
  File "/usr/lib/python3.3/urllib/request.py", line 451, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.3/urllib/request.py", line 696, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/usr/lib/python3.3/urllib/request.py", line 479, in open
    response = meth(req, response)
  File "/usr/lib/python3.3/urllib/request.py", line 591, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python3.3/urllib/request.py", line 511, in error
    result = self._call_chain(*args)
  File "/usr/lib/python3.3/urllib/request.py", line 451, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.3/urllib/request.py", line 686, in http_error_302
    self.inf_msg + msg, headers, fp)
urllib.error.HTTPError: HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop.
The last 30x error message was:
Found

我的问题是:为什么会发生这种情况,我该如何避免?

My question is: why is it happening and how can I avoid it?

推荐答案

发生这种情况可能是因为目标站点使用 cookie 并在您不发送 cookie 的情况下重定向您.

This happens probably because the destination site uses cookies and redirect you in case you don't send cookies.

你可以使用的东西是这样的:

What you can use is something like that :

from http.cookiejar import CookieJar

url = "http://www.tradegate.de/orderbuch.php?isin=CH0012138530"

req = urllib.request.Request(url, None, {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8','Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3','Accept-Encoding': 'gzip, deflate, sdch','Accept-Language': 'en-US,en;q=0.8','Connection': 'keep-alive'})

cj = CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
response = opener.open(req)
response.read()

这样,您就支持 Cookie,网站将允许您访问该页面 :-)

This way, you support Cookies and website will allow you to get the page :-)

另一种方法是使用 requests 包,它使用起来非常简单.在你的情况下,它会导致:

Another way would be to use the requests package which is really simplest to use. In your case, it would lead to :

import requests

url = "http://www.tradegate.de/orderbuch.php?isin=CH0012138530"
r = requests.get(url, headers={'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}, timeout=15)
print(r.content)

这篇关于Python3:使用 urllib 时出现 HTTP 错误 302的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆