2014-01-29 32 views
2

我需要登陆网站白衣pycurl,进行重定向,并打印最终网址,我写这篇文章的Python代码:蟒蛇pycurl获得最终的URL重定向

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)

+0

你真的需要使用'pycurl'吗?如果没有,请尝试使用'requests',就像我记得的那样,解决方案做你想做的事,真的更加明显。 – zmo

+0

是的,我需要使用pycurl,是非常快速的图书馆! – kingcope

+0

这里有一些人在PHP中实现的方式:http://forums.devshed.com/php-development-5/curl-get-final-url-after-inital-url-redirects-544144.html好东西,卷曲这就是说,图书馆在不同的语言中表现相同。 – zmo

回答

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添加回去)