Home > Enterprise >  python request does not return what was requested
python request does not return what was requested

Time:11-19

Yo! I am learning requests in python and i get a problem!

when i try to get status code from the url i dont receive answer

When I run the program, it doesn't finish or return anything. Below is a picture of the terminal and my code.

import requests
import socket


old_getaddrinfo = socket.getaddrinfo
def new_getaddrinfo(*args, **kwargs):
    responses = old_getaddrinfo(*args, **kwargs)
    return [response
            for response in responses
            if response[0] == socket.AF_INET]
socket.getaddrinfo = new_getaddrinfo


res = requests.get('https://www.americanas.com.br/')

print(res.status_code)
if res.status_code ==200:
    print('O servidou disse OK')
else:
    print('O servidor falhou!')

observation:

I've also tried without the first part of the code,

CodePudding user response:

Your code keeps waiting for a response. Try adding timeout in your request.

res = requests.get('https://www.americanas.com.br/', timeout=5)

Using this, your request will last for only 5 seconds before throw and exception.

CodePudding user response:

It seems like the server is not responding without a user agent header. Just set it to the chrome one.:

res = requests.get('https://www.americanas.com.br/', headers={"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36"})
  • Related