为什么我不能使用Python加载此页面?

时间:2014-10-27 22:11:53

标签: python urllib

如果我使用urllib加载此网址(https://www.fundingcircle.com/my-account/sell-my-loans/),我会收到400状态错误。

e.g。以下返回400错误

>>> import urllib
>>> f = urllib.urlopen("https://www.fundingcircle.com/my-account/sell-my-loans/")
>>> print f.read()

但是,如果我将网址复制并粘贴到我的浏览器中,我会看到一个包含我想要查看的信息的网页。

我尝试过尝试,除了,然后阅读错误。但返回的数据只是告诉我该页面不存在。 e.g。

import urllib
try:
    f = urllib.urlopen("https://www.fundingcircle.com/my-account/sell-my-loans/")
except Exception as e:
    eString = e.read()
    print eString

为什么Python不能加载页面?

1 个答案:

答案 0 :(得分:5)

如果Python被赋予404状态,那就是因为服务器拒绝向您提供该页面。

为什么很难知道,因为服务器是黑盒子。但是,您的浏览器为服务器提供的不仅仅是URL,它还为其提供了一组HTTP标头。服务器很可能会根据一个或多个标头的内容改变行为。

您需要查看浏览器开发工具并查看浏览器发送的内容,然后尝试从Python复制某些这些标头。明显的候选人是User-Agent标题,后跟AcceptCookie标题。

但是,在这种特定情况下,服务器正在响应401 Unauthorized;你有一个登录页面。它为浏览器和Python都做到了这一点:

>>> import urllib
>>> urllib.urlopen('https://www.fundingcircle.com/my-account/sell-my-loans/')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib.py", line 87, in urlopen
    return opener.open(url)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib.py", line 208, in open
    return getattr(self, name)(url)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib.py", line 451, in open_https
    return self.http_error(url, fp, errcode, errmsg, headers)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib.py", line 372, in http_error
    result = method(url, fp, errcode, errmsg, headers)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib.py", line 683, in http_error_401
    errcode, errmsg, headers)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib.py", line 381, in http_error_default
    raise IOError, ('http error', errcode, errmsg, headers)
IOError: ('http error', 401, 'Unauthorized', <httplib.HTTPMessage instance at 0x1066f9a28>)

但Python的urllib没有401状态代码的处理程序,并将其转换为异常。

响应正文包含登录表单;你必须编写代码才能在这里登录,并且可能跟踪cookie。

使用更专业的工具可以轻松完成任务。您可以使用robobrowser加载页面,解析表单并提供填写表格的工具,然后为您发布表单并跟踪保持登录所需的cookie。它建立在优秀的requestsBeautifulSoup库。