有时我需要解析提供的Beautiful Soup和Requests URL:
当然,这些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。谢谢。
最佳答案
它位于url
对象的response
属性中。
>>> 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/