关于在python中处理重定向

时间:2013-02-13 11:27:14

标签: python redirect urllib2

我是python的新手,正在尝试学习一些新模块。幸运或不幸的是,我拿起了urllib2模块并开始使用一个导致我出现问题的URL。

首先,我创建了Request对象,然后在响应对象上调用了Read()。它失败了。原来它被重定向,但错误代码仍然是200.不知道发生了什么。这是代码 -

def get_url_data(url):
    print "Getting URL " + url
    user_agent = "Mozilla/5.0 (Windows NT 6.0; rv:14.0) Gecko/20100101 Firefox/14.0.1"
    headers = { 'User-Agent' : user_agent }
    request = urllib2.Request(url, str(headers) )

    try:    
        response = urllib2.urlopen(request)
    except urllib2.HTTPError, e:
        print response.geturl()
        print response.info()
        print response.getcode()
        return False;
    else:
        print response
        print response.info()
        print response.getcode()
        print response.geturl()
        return response

我用http://www.chilis.com“调用上述函数。

我期待收到301,302或303,但我看到200.这是我看到的回复 -

Getting URL http://www.chilis.com
<addinfourl at 4354349896 whose fp = <socket._fileobject object at 0x1037513d0>>
Cache-Control: private
Server: Microsoft-IIS/7.5
SPRequestGuid: 48bbff39-f8b1-46ee-a70c-bcad16725a4d
X-SharePointHealthScore: 0
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 14.0.0.6120
X-MS-InvokeApp: 1; RequireReadOnly
Date: Wed, 13 Feb 2013 11:21:27 GMT
Connection: close
Content-Length: 0
Set-Cookie: BIGipServerpool_http_chilis.com=359791882.20480.0000; path=/

200
http://www.chilis.com/(X(1)S(q24tqizldxqlvy55rjk5va2j))/Pages/ChilisVariationRoot.aspx?AspxAutoDetectCookieSupport=1

有人可以解释这个URL是什么以及如何处理这个?我知道我可以使用Diveintopython.net的“处理重定向”部分,但是那个页面上的代码也看到相同的响应200.

编辑:使用DiveintoPython中的代码,我看到它是一个临时重定向。我不明白的是为什么代码中的HTTP Errorcode是200.那不应该是实际的返回代码吗?

EDIT2:现在我看到它更好了,它根本不是一个奇怪的重定向。我正在编辑标题。

EDIT3:如果urllib2自动跟随重定向,我不知道为什么以下代码没有获得chilis.com的首页。

docObj = get_url_data(url)
doc = docObj.read()
soup = BeautifulSoup(doc, 'lxml')
print(soup.prettify())

如果我使用浏览器最终最终被重定向到的网址(http://www.chilis.com/EN/Pages/home.aspx“)。

1 个答案:

答案 0 :(得分:2)

urllib2会自动跟踪重定向,因此您看到的信息来自重定向到的页面。

如果您不希望它遵循重定向,则需要继承urllib2.HTTPRedirectHandler。以下是有关如何执行此操作的相关SO帖子:How do I prevent Python's urllib(2) from following a redirect

关于编辑3:看起来www.chilis.com需要接受cookie。这可以使用urllib2来实现,但我建议安装requests模块(http://pypi.python.org/pypi/requests/)。

以下似乎完全符合您的要求(没有任何错误处理):

import requests

r = requests.get(url)
soup = BeautifulSoup(r.text, 'lxml')
print(soup.prettify())