理解Requests库的异常

image.png
image.png

通用代码框架

  1. import requests
  2. def getHTMLText(url):
  3. try:
  4. r = requests.get(url, timeout=30)
  5. r.raise_for_status() # 如果状态不是200,引发HTTPError异常
  6. r.encoding = r.apparent_encoding
  7. return r.text
  8. except:
  9. return "error!"
  10. if __name__ == "__main__":
  11. url = "http://www.baidu.com"
  12. print(getHTMLText(url))