0

everybody. I'm learning Python from a few weeks. I have a problem with the requests library. I wrote a short code which asks for a website address. If the page exists, it is written to the file good.txt, if it does not exist it should be written to the wrong.txt file. What's wrong with this code?

import requests


website = input('First website to check:  ')

website1 = 'http://'+website

a = requests.get(website1)



try:
    a.status_code  == 200
    with open("good.txt", "a", encoding = "UTF-8") as file:
         file.write(website1)

except requests.RequestException:
    with open("wrong.txt", "a", encoding = "UTF-8") as file:
         file.write(website1)

Thanks for the advice.

mateoo88
  • 33
  • 7

2 Answers2

0

You need to make an if statement

try:
    a = requests.get(website1)
    if a.status_code  == 200:
        with open("good.txt", "a", encoding = "UTF-8") as file:
            file.write(website1)
    else:
        with open("wrong.txt", "a", encoding = "UTF-8") as file:
            file.write(website1)

except requests.RequestException:
    with open("wrong.txt", "a", encoding = "UTF-8") as file:
        file.write(website1)

Edit: also fixed your try catch code

badcod3r
  • 61
  • 3
0

Using your try/except block, you have to make the request in the try block.

import requests


website = input('First website to check:  ')

website1 = 'http://'+website
try:
    a = requests.get(website1)
    a.status_code  == 200
    with open("good.txt", "a", encoding = "UTF-8") as file:
         file.write(website1)

except requests.RequestException:
    with open("wrong.txt", "a", encoding = "UTF-8") as file:
         file.write(website1)
collinsuz
  • 439
  • 1
  • 4
  • 13