Request response issue using python3

I check my domains with requests (rest) in the for loop. But if 200 not return, i m getting connection refused, connection timeout etc errors. How can I list 200 returning domains and not returning ?


URL = ['example.com', 'test.com']

for i in URL:
    try:
        response = requests.get(i, headers=headers)
        response.raise_for_status()
        if response == 200:
            print("valid")
    except requests.exceptions.RequestException as errex:
        print("invalid", URL)

I think you may want:

except requests.exceptions.HTTPError as errex::

You also don’t need the if response == 200: if you are calling raise_for_status. You should either call raise_for_status() OR check teh status code by hand, you don’t need to do both. But if you want to check the response, you want:

if response.status_code == 200

I got all this from the requests quickstart – my suggestion is to read the docs carefully, and implement your code one line at a time, testing as you go, especially when trying to figure out a new library.

Also: post comoplete code samples – yours had missing imports and multiple small bugs. Here’s code that works:

import requests

URLS = ['example.com', 'test.com', 'http://google.com']

headers = {}
for url in URLS:
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        if response.status_code == 200:
            print("valid", url)
    except requests.exceptions.RequestException as errex:
        print("invalid", url)
1 Like