如何检查网站是否可以通过 www
访问。例如以下网址:
https://corteva.in/
无法访问。但是当输入像(带有www)时:
https://www.corteva.in/
它在浏览器中正确显示。有没有办法用 python 来检查这个?
我尝试了以下方法:
import socket
socket.gethostbyname('www.corteva.in')
socket.gethostbyname('corteva.in')
两者都解析为某个IP地址。但是,当在 https://corteva.in
等浏览器中加载时,浏览器永远无法加载 Web 服务。
最佳答案
import requests
def attempt_connection(url):
try:
r = requests.get(url, timeout=1)
print(f"Website {url} connected with status code {r.status_code}.")
except requests.exceptions.ConnectTimeout as e:
print(f"Website {url} timed out.")
attempt_connection("https://corteva.in/")
attempt_connection("https://www.corteva.in/")
输出:
Website https://corteva.in/ timed out.
Website https://www.corteva.in/ connected with status code 200.
关于python - 检查网站是否可以通过 www 或不通过 www 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59998676/