2014-01-29 28 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添加回去)