繁体   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