python pycurl获取最终的url重定向

时间:2014-01-29 23:26:18

标签: python pycurl

我需要访问网站whit pycurl,按照重定向,并打印最终网址,我写这个python代码:

c = pycurl.Curl()
c.setopt(c.URL, 'http://localhost/redirect.php')
c.setopt(c.HTTPPOST, values)
c.setopt(c.WRITEFUNCTION, buf_pagina.write)
c.setopt(c.HEADERFUNCTION, buf_header.write)
c.setopt(c.CONNECTTIMEOUT, 30)
c.setopt(c.AUTOREFERER,1)
c.setopt(c.FOLLOWLOCATION, 1)
c.setopt(c.COOKIEFILE, '')
c.setopt(c.TIMEOUT, 30)
c.setopt(c.USERAGENT, '')
c.perform()

我需要打印最终网址,我该怎么做?感谢。

解决方案如下:url_effective = c.getinfo(c.EFFECTIVE_URL)

1 个答案:

答案 0 :(得分:5)

这是我在评论中链接的PHP脚本的改编:

import pycurl
import sys
import StringIO

o = StringIO.StringIO()
h = StringIO.StringIO()

c = pycurl.Curl()
c.setopt(c.URL, 'http://stackoverflow.com/questions/21444891')
# c.setopt(c.HTTPPOST, values)
c.setopt(c.WRITEFUNCTION, o.write)
c.setopt(c.HEADERFUNCTION, h.write)
c.setopt(c.CONNECTTIMEOUT, 30)
c.setopt(c.AUTOREFERER,1)
c.setopt(c.FOLLOWLOCATION, 1)
c.setopt(c.COOKIEFILE, '')
c.setopt(c.TIMEOUT, 30)
c.setopt(c.USERAGENT, '')
c.perform()

h.seek(0)

location = ""

for l in h:
    if "Location" in l:
        location = l.split(": ")[-1]

print location

但是,正如这个例子所示,你可能并不总是拥有完整的URI,只有URI的路径部分(但如果是这样的话,很容易将fqdn添加回来)