簡體   English   中英

python requests.get 無效 URL

[英]python requests.get with invalid URL

我正在編寫一個短代碼來檢查 url 是否有效。 但是,當我檢查無效的 URL 時,它不會響應任何錯誤的狀態代碼。 它只是不運行代碼。

我可以通過以下代碼獲得一些幫助嗎?

import requests
import string

# Welcome to IsItDown.py!
# Please write a URL or URLs you want to check. (separated by a comma)
#
# input()
#
# <check for valid URL>
#
# Do you want to start over? (y/n)
# if y:
# elif n: print(Okay. Bye!)
# else: That's not a valid answer

def url_check(urls):
  for url in urls:
    resp = requests.get(url)
    if resp.status_code == 200:
      print(f"{url} is up!")
    else:
      raise Exception(f"{url} is down!")


print("Welcome to IsItDown.py!")

urls = ['google.com .', '   na1v2e12312r.com ']

for index, item in enumerate(urls):
  item = item.strip(string.punctuation).strip()
  if "http" not in item:
    item = "http://" + item
  urls[index] = item

print(urls) 

try:
  url_check(urls)

except Exception as e:
  print(e)

由於這是您嘗試訪問無效的 URL 時遇到的錯誤:

NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7efc88f33b50>: 
    Failed to establish a new connection: [Errno -2] Name or service not known')

這意味着為了捕獲錯誤並指示 URL 無效,您必須像當前正在使用的那樣使用tryexcept ,除非您會捕獲該特定錯誤:

try:
    resp = requests.get(url)
except NewConnectionError:
    print(f'Invalid URL: "{url}"')
    # at this point, you can continue the loop to the next URL if you want

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM