我只想着如何模仿浏览器,比如Chrome,用
Python检测网站的协议.例如,我们在地址栏上键入“stackoverflow.com”,然后按Enter,浏览器可以自动检测并将URL更改为“
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中检测相同内容,请使用请求库,如下所示:
>>> import requests
>>> r = requests.get('https://stackoverflow.com') # first we try http
>>> r.url # check the actual URL for the site
'https://stackoverflow.com/'
要了解URL的更改方式,请查看历史记录对象,您将看到301响应,这意味着URI具有moved permanently到新地址.
>>> r.history[0]
>>> r.history[0].url # this is the original URL we tried
'https://stackoverflow.com/'