python获取网站时间戳
时间: 2024-12-08 08:11:40 浏览: 92
在Python中,如果你想获取某个网页的HTTP头中的Last-Modified或ETag(Expires)等时间戳,通常使用`requests`库来进行网络请求。例如,你可以这样做:
```python
import requests
# 获取网页内容
response = requests.get('http://www.example.com')
# 查找Last-Modified或ETag字段的时间戳
last_modified = response.headers.get('Last-Modified')
if last_modified:
# 时间戳通常是HTTP协议中的RFC 1123格式,可以转化为datetime对象
timestamp_rfc1123 = last_modified
timestamp_datetime = datetime.datetime.strptime(timestamp_rfc1123, '%a, %d %b %Y %H:%M:%S GMT')
etag = response.headers.get('ETag')
if etag:
# ETag通常包含版本信息,不是精确的时间戳
pass
# 或者,如果服务器支持,可以获取服务器发送给浏览器的响应头中的Date字段
date_header = response.headers.get('Date')
if date_header:
# Date也是RFC 1123格式
timestamp_rfc1123 = date_header
timestamp_datetime = datetime.datetime.strptime(timestamp_rfc1123, '%a, %d %b %Y %H:%M:%S GMT')
# 使用上述得到的时间戳进行相应操作
```
注意,你需要安装`requests`库才能运行以上代码,如果没有安装可以使用`pip install requests`命令安装。另外,某些网站可能会禁用这些信息的提供,或者它们可能有特定的策略来管理返回的时间戳。
阅读全文
相关推荐















