Python遵循重定向然后下载页面?

时间:2012-01-11 22:20:14

标签: python html web-scraping

我有以下python脚本,它工作得很漂亮。

import urllib2

url = 'http://abc.com' # write the url here

usock = urllib2.urlopen(url)
data = usock.read()
usock.close()

print data

但是,我给它的一些URL可能会重定向它2次或更多次。在加载数据之前,如何让python等待重定向完成。 例如,将上述代码与

一起使用时
http://www.google.com/search?hl=en&q=KEYWORD&btnI=1

这是在谷歌搜索中点击我的幸运按钮的等价物,我得到:

>>> url = 'http://www.google.com/search?hl=en&q=KEYWORD&btnI=1'
>>> usick = urllib2.urlopen(url)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 400, in open
    response = meth(req, response)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
>>> 

我已经尝试了(网址,数据,超时)但是,我不确定要放在那里。

编辑: 我实际上发现如果我不重定向并且只使用第一个链接的标题,我可以抓住下一个重定向的位置并将其用作我的最终链接

3 个答案:

答案 0 :(得分:18)

使用具有更好的API来控制重定向处理的Requests库可能会更好:

http://docs.python-requests.org/en/latest/user/quickstart/#redirection-and-history

请求:

http://pypi.python.org/pypi/requests/(urllib替代人类)

答案 1 :(得分:2)

使用requests作为其他答案状态,这是一个示例。重定向将位于r.url。在下面的示例中,http被重定向到https

对于HEAD:

In [1]:     import requests
   ...:     r = requests.head('http://github.com', allow_redirects=True)
   ...:     r.url

Out[1]: 'https://github.com/'

GET:

In [1]:     import requests
   ...:     r = requests.get('http://github.com')
   ...:     r.url

Out[1]: 'https://github.com/'

注意HEAD你必须指定allow_redirects,但如果你不指定,你可以在标题中得到它,但不建议这样做。

In [1]: import requests

In [2]: r = requests.head('http://github.com')

In [3]: r.headers.get('location')
Out[3]: 'https://github.com/'

下载页面,您需要获取GET,然后您可以使用r.content

访问该页面

答案 2 :(得分:-3)

你绝对必须这样做吗?如何使用twill(http://twill.idyll.org/)之类的东西 - 让你想要做的事情非常简单(而且是Python)。

相关问题