简体   繁体   中英

Python requests header not working - Checked Chrome developer tools -> Network

This is my python code:

import requests
from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    url = 'https://google.co.in'
    headers = {
        'User-Agent':'blahblahblah'
    }
    r = requests.get(url, headers=headers)

    return 'check terminal'

So this is the way to change request headers in python requests. But if I open the url and see developer options > Network > Request headers. I see default as user agent. Means it simply doesn't work.

The request you're making is by the server, not the client (the web browser). The index page served by flask goes to a client. The client doesn't make the requests.get request you've written here, instead the server does.

Instead, the client only requests whatever you're returning from the route, which here is 'check terminal' (which should not work, and should be something in the lines of return jsonify(result='check terminal') ), and is not concerned about what the server is doing internally.

So as @brunns has commented, these two requests are different. If you want to check the headers of your request, maybe try httpbin.org .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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