【问题标题】:URL requests with Python使用 Python 的 URL 请求
【发布时间】:2021-03-28 19:31:18
【问题描述】:

我刚刚完成了一个简短的程序来检查 URL 是否有效以及可访问性。但是,无论如何从 try/except 块不能正常工作 我不知道为什么。即使我输入正确的 URL,它也不会打印出我需要的结果。

我将列出下面的代码,只需检查 try/except 块:

import os
import requests
import string


def url_check(url):
  try:
    resp = requests.get(url)
    if resp.requests.status_code == 200:
      print(f">>> {url} is up!")
    else:
      print(f">>> {url} is down!") # Normal URL but down
  except:
        print(f">>> {url} is down!") # invalid URL
  return


def restart():
  print("\nDo you want to start over? y/n", end=' ')
  choice = input()

  if choice.lower() == 'y':
    main()
  elif choice.lower() == 'n':
    print("Okay. Bye!")
    exit()
  else:
    print("That's not a valid answer")
    restart()


def main():
  os.system('clear')
  print("Welcome to IsItDown.py!")
  print("Please write a URL or URLs you wnat to check. (separated by a comma)")

  while True:
    urls = input().split(',')

    for url in urls:
      url = url.strip(string.punctuation).strip().lower()
      if "." not in url:
        print(f"{url} is not a valid URL")
        break 
      else:
        if "http" not in url:
          url = "http://" + url
          url_check(url)
    restart()

if __name__ == "__main__":
  main()

【问题讨论】:

  • 永远不要用黑框和通用 try/except 完全隐藏异常。至少打印出错误信息。
  • @KlausD.Do you mean by 'except Exception as e:' ?
  • 更重要的部分是额外的print(e) 或类似的。

标签: python url python-requests


【解决方案1】:

您的 if 语句应如下所示。

if resp.status_code == 200:

因为它已经是一个请求实例

【讨论】:

    【解决方案2】:

    如果你为你的 if 语句取出请求,它工作正常!

    def url_check(url):
        try:
            resp = requests.get(url)
            if resp.status_code == 200:
    

    【讨论】:

      猜你喜欢
      • 2017-11-19
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多