简体   繁体   English

使用 requests.get 获得重定向 url

[英]Using requests.get to get redirected url

I have a super long url, and I'm trying to print its final destination.我有一个超长的 url,我正在尝试打印它的最终目的地。 I've got:我有:

import requests
url = "https://l.facebook.com/l.php?u=https%3A%2F%2Fwww.washingtonpost.com%2Fscience%2F2020%2F04%2F29%2Fcoronavirus-detection-dogs%2F%3Ffbclid%3DIwAR00eT4EHsWC9986GUSox_7JS7IIg2wAan-tB-NteYJd8I4xckmxnfaNGEI&h=AT0cs4gTKPZlkSElC2uhoDYR98lsONooq_ZUFIK87khBmtZE_3r8j25EfioBPAdp-O8o7efRVG9uB-doy9vLT-AccZMrxnfpEiSYRmA2LTL21IU15bP_PTVw4SSibS1A_uE8bU-ROJexKgdk68VSTtE&__tn__=H-R&c[0]=AT3BNcTNFE13IJu3naJmxTRdJTWtO4O4L0_-nimmzcXpYv3N536YRpQZLg-v2FtP_Oz2DZZpBN6XQPb89JNJTsYFXlK8-1g4xdDLi1T_lfowpI5Ooh8kuLpciLiQ9t-ZmMd2CTUWaGZ_Y_JU0OEvVWfLLfjDq4VOzUtETBcvXHw2ZvQnTQ"
r = requests.get(url, allow_redirects=False)
print(r.headers['Location'])

It should get me to https://www.washingtonpost.com/science/2020/04/29/coronavirus-detection-dogs/?fbclid=IwAR00eT4EHsWC9986GUSox_7JS7IIg2wAan-tB-NteYJd8I4xckmxnfaNGEI .它应该让我到达https://www.washingtonpost.com/science/2020/04/29/coronavirus-detection-dogs/?fbclid=IwAR00eT4EHsWC9986GUSox_7JS7IIg2wAan-tB-NteYJd8I4xckmxnfaNGEI But I get the same URL I put in.但是我得到了与我输入的相同的 URL。

(By the way, if anyone happens to know how to do this in Javascript, that would be awesome, but Google tells me that's not possible.) (顺便说一句,如果有人碰巧知道如何在 Javascript 中执行此操作,那就太棒了,但 Google 告诉我这是不可能的。)

Since you just want to get the URL, requests here cant be that much of help.由于您只想获得 URL,因此此处的requests不会有太大帮助。 Instead, you can use urllib.parse :相反,您可以使用urllib.parse

import urllib.parse as url_parse


url = <https://l.facebook.com/l.php?u=https...>
news_link = url_parse.unquote(url).split("?u=")[1]

# if you wish to delete Facebook Id, you can add this too
news_link  = url_parse.unquote(url).split("?u=")[1].split("?fbclid")[0]
print(news_link)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM