【问题标题】:Return last URL in sequence of redirects返回重定向序列中的最后一个 URL
【发布时间】:2013-06-12 17:41:22
【问题描述】:

我有时需要解析这样提供的 Beautiful Soup 和请求 URL:

http://bit.ly/sdflksdfwefwe

http://stup.id/sdfslkjsfsd

http://0.r.msn.com/sdflksdflsdj

当然,这些 URL 通常会“解析”为规范 URL,例如 http://real-website.com/page.html。如何获取解析/重定向链中的最后一个 URL?

我的代码一般是这样的:

from bs4 import BeautifulSoup
import requests

response = requests.get(url)
soup = bs4.BeautifulSoup(response.text, from_encoding=response.encoding)
canonical_url = response.??? ## This is what I need to know

请注意,我并不是要查询 http://bit.ly/bllsht 来查看它的去向,而是当我使用 Beautiful Soup 已经解析它返回的页面时,获取规范重定向链中最后一个 URL。

谢谢。

【问题讨论】:

    标签: python python-requests


    【解决方案1】:

    它位于 response 对象的 url 属性中。

    >>> response = requests.get('http://bit.ly/bllsht')
    >>> response.url
      > u'http://www.thenews.org/sports/well-hey-there-murray-state-1-21-11-1.2436937'
    

    您可以在“Quick Start” page中轻松找到此信息。

    【讨论】:

    • 如此简单!谢谢!
    • 感谢您使用链接进行编辑。在我看来,url 属性将是在 get() 方法中指定的 URL。
    • 你知道如何为 urllib2 做同样的事情吗?
    • @Pythoner1234 请下次再问一个问题(或者,更好的是,先搜索,因为已经有类似的问题了)。基本上,答案是:您必须手动执行此操作。
    猜你喜欢
    • 1970-01-01
    • 2012-03-19
    • 2010-12-29
    • 2012-05-21
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    相关资源
    最近更新 更多