【问题标题】:python pycurl get final url redirectpython pycurl 获取最终的 url 重定向
【发布时间】:2014-02-22 01:42:32
【问题描述】:

我需要访问带有 pycurl 的网站,遵循重定向,并打印最终 url,我编写了这个 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)

【问题讨论】:

  • 你真的需要使用pycurl吗?如果没有,请尝试使用requests,据我所知,做你想做的事情的解决方案非常明显。
  • 是的,我需要使用 pycurl,是非常快的库!
  • 这是一些人在 php 中实现的一种方式:forums.devshed.com/php-development-5/… curl 的好处,就是库在不同语言中的行为相同。

标签: python pycurl


【解决方案1】:

这是我在 cmets 中链接的 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 添加回来)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 2014-12-07
    • 2021-09-15
    • 2011-03-05
    • 2013-02-03
    • 1970-01-01
    相关资源
    最近更新 更多