gpt4 book ai didi

python - urlerror 和 ssl.CertificateError

转载 作者:行者123 更新时间:2023-12-01 08:28:19 27 4
gpt4 key购买 nike

我有以下代码:

from urllib.request import urlopen
from urllib.error import HTTPError, URLError
from bs4 import BeautifulSoup

# target = "https://www.rolcruise.co.uk/cruise-detail/1158731-hawaii-round-trip-honolulu-2020-05-23"
target = "https://www.rolcruise.co.uk"

try:
html = urlopen(target)
except HTTPError as e:
print("You got a HTTP Error. Something wrong with the path.")
print("Here is the error code: " + str(e.code))
print("Here is the error reason: " + e.reason)
print("Happy for the program to end here"
except URLError as e:
print("You got a URL Error. Something wrong with the URL.")
print("Here is the error reason: " + str(e.reason))
print("Happy for the program to end here")
else:
bs_obj = BeautifulSoup(html, features="lxml")
print(bs_obj)

如果我故意在输入网址的某些部分时犯错误,则 urlerror 处理工作正常,即如果我故意输入“htps”而不是“https”,或者“ww”而不是“www”,或者“u” ”而不是“英国”。例如

target = "https://www.rolcruise.co.u"

但是,如果主机名(“rolcruise”)或 url 的“co”部分输入错误,则 urlerror 将不起作用,并且我会收到一条错误消息,显示 ssl.CertificateError。例如

target = "https://www.rolcruise.c.uk"
  1. 我不明白为什么 URLError 不能涵盖 url 中某处出现拼写错误的所有情况?

  2. 鉴于这种情况正在发生,处理 ssl.CertificateError 的下一步措施是什么?

感谢您的帮助!

最佳答案

将 ssl 引入您的命名空间以启动:

import ssl

然后你就可以捕获这种异常:

try:
html = urlopen(target)
except HTTPError as e:
print("You got a HTTP Error. Something wrong with the path.")
print("Here is the error code: " + str(e.code))
print("Here is the error reason: " + e.reason)
print("Happy for the program to end here"
except URLError as e:
print("You got a URL Error. Something wrong with the URL.")
print("Here is the error reason: " + str(e.reason))
print("Happy for the program to end here")
except ssl.CertificateError:
# Do your stuff here...
else:
bs_obj = BeautifulSoup(html, features="lxml")
print(bs_obj)

关于python - urlerror 和 ssl.CertificateError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54083486/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com