我只是在想我们如何模仿浏览器(比如 Chrome)如何使用 Python 检测网站的协议。例如我们在地址栏输入“stackoverflow.com”,然后回车,浏览器会自动检测到并将url更改为“https://stackoverflow.com https://stackoverflow.com“(添加网站的协议),我想知道我们如何在Python中做到这一点,就像:
url = "stackoverflow.com"
browser = Browser (url) # Browser is a class that we can get website content from url, get its protocol,...
print browser.protocol
https
有没有任何库或包可以帮助做到这一点?多谢。
编辑:我的问题很独特,因为其他问题询问如果我们输入http如何重定向到https,正如我提到的,我们可以在第一阶段自动检测而无需虚拟协议吗?
它适用于 stackoverflow,因为当您第一次在端口 80(http 端口)上访问 stackoverflow.com 时,stackoverflow 的服务器会通知浏览器该链接已永久移至 https。
要在 Python 中检测相同的内容,请使用requests
库,像这样:
>>> import requests
>>> r = requests.get('http://stackoverflow.com') # first we try http
>>> r.url # check the actual URL for the site
'https://stackoverflow.com/'
要了解 URL 如何更改,请查看历史记录对象,您将看到 301 响应,这意味着 URI 发生了变化永久移动 https://httpstatuses.com/301到一个新地址。
>>> r.history[0]
<Response [301]>
>>> r.history[0].url # this is the original URL we tried
'http://stackoverflow.com/'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)