Search code examples
pythonhtmlpython-requests-html

r.history returning an empty list [python]


Here is the code in main.py

import requests

URL = 'localhost:80'
if 'http' not in URL: URL = 'http://'+ URL
r = requests.get(URL)
for resp in r.history:
    print(r.url)

Here is the code in webserver.py

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return '<script>location.href = "https://youtube.com"</script>'

if __name__=='__main__':
    app.run('0.0.0.0', 80)

r.history returns an empty list when I run main.py


Solution

  • If you wanna get the redicrection url:

    app.py

    from flask import Flask, redirect
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return redirect('https://python.org')
    
    if __name__=='__main__':
        app.run('0.0.0.0', 80)
    

    req.py

    import requests
    
    URL = 'localhost:80'
    r = requests.get("http://localhost:80", allow_redirects=True)
    print(r.url)
    

    If you wanna get the history of the request

    import requests
    
    URL = 'localhost:80'
    r = requests.get("http://localhost:80", allow_redirects=True)
    print(r.history)