request.get的Python错误

时间:2015-08-13 18:00:49

标签: python python-requests

我正在尝试编写一个Python脚本,使我能够访问网页并从该页面下载文件。我的第一次尝试只是到达那个页面,我尝试了以下代码:

import requests

url = 'https://www.google.com/?gws_rd=ssl' #using google as an example

r = requests.get(url)

print(r.url)

我收到了这个错误:

runfile('C:/Users/ME/Desktop/TMS502.py', wdir='C:/Users/ME/Desktop')
Traceback (most recent call last):

  File "<ipython-input-23-bc585dcceef8>", line 1, in <module>
    runfile('C:/Users/ME/Desktop/TMS502.py', wdir='C:/Users/ME/Desktop')

  File "C:\Users\ME\AppData\Local\Continuum\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 585, in runfile
    execfile(filename, namespace)

  File "C:/Users/ME/Desktop/TMS502.py", line 16, in <module>
    r = requests.get(url)

  File "C:\Users\ME\AppData\Local\Continuum\Anaconda\lib\site-packages\requests\api.py", line 55, in get
    return request('get', url, **kwargs)

  File "C:\Users\ME\AppData\Local\Continuum\Anaconda\lib\site-packages\requests\api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)

  File "C:\Users\ME\AppData\Local\Continuum\Anaconda\lib\site-packages\requests\sessions.py", line 456, in request
    resp = self.send(prep, **send_kwargs)

  File "C:\Users\ME\AppData\Local\Continuum\Anaconda\lib\site-packages\requests\sessions.py", line 559, in send
    r = adapter.send(request, **kwargs)

  File "C:\Users\ME\AppData\Local\Continuum\Anaconda\lib\site-packages\requests\adapters.py", line 375, in send
    raise ConnectionError(e, request=request)

ConnectionError: HTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: /?gws_rd=ssl (Caused by <class 'socket.error'>: [Errno 10054] An existing connection was forcibly closed by the remote host)

有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:3)

您收到该错误是因为远程端(在本例中为Google)正在关闭您的请求,否则您将无法再与其建立连接。

从错误:

ConnectionError: HTTPSConnectionPool(host='www.google.com', port=443): 
Max retries exceeded with url: /?gws_rd=ssl 
(Caused by <class 'socket.error'>: [Errno 10054] An existing connection was forcibly closed by the remote host)

我们可以查看source的提示:

class MaxRetryError(RequestError):
    """Raised when the maximum number of retries is exceeded.
    :param pool: The connection pool
    :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`
    :param string url: The requested Url
    :param exceptions.Exception reason: The underlying error
    """

    def __init__(self, pool, url, reason=None):
        self.reason = reason

        message = "Max retries exceeded with url: %s (Caused by %r)" % (
            url, reason)

        RequestError.__init__(self, pool, url, message)

尝试另一个示例主机,您的代码应该可以使用,例如https://example.org

错误消息&#34;远程主机&#34;强制关闭现有连接。来自您的操作系统(Windows),请求正在向您显示此文本以试图提供帮助。

答案 1 :(得分:-3)

无论如何,你是否还在烦恼:

from urllib2 import urlopen
u = urlopen("https://www.google.com/?gws_rd=ssl")
data = u.read()
u.close()

也许这会工作。