Python:如何转到 link 并打开它(如果存在)

Python: How to go to a link and open it if it exists

我找到了这段代码:

import webbrowser

webbrowser.open('http://eample.com')

如何修改它,使其仅在 return 代码为 200 时才打开 link?

使用requests包发送一个HEAD请求到想要的位置,然后创建一个if

if requests.head(url).status_code == 200: webbrowser.open(url) # open url if status is 200