gpt4 book ai didi

python - 返回重定向序列中的最后一个 URL

转载 作者:太空狗 更新时间:2023-10-30 02:32:38 27 4
gpt4 key购买 nike

有时我需要使用 Beautiful Soup 和 Requests 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。

谢谢。

最佳答案

它位于 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 中轻松找到此信息.

关于python - 返回重定向序列中的最后一个 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17062151/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com