Find final redirected url in Python

2020-05-03 02:14发布

问题:

import requests

def extractlink():
    with open('extractlink.txt', 'r') as g:
        print("opened extractlink.txt for reading")
        contents = g.read()
        headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'}
        r = requests.get(contents, headers=headers)
        print(("Links to " + r.url))
        time.sleep (2)

Currently, r.url is just linking to the url found in 'extractlink.txt'

I'm looking to fix this script to find the final redirected url and print the result. It appears the issue lies somewhere in the request for the URL, despite trying many alternatives and troubleshooting steps, my issue doesn't seem to be solved like the rest.

When debugging, r.history reads as [] and r.status_code reads as 403 even though the link redirects as a 302 in browser. Any ideas?

(extractlink.txt is just a one line file with a link to http://butterup.teechip.icu/, enter with your own caution, spam website)