Skip to main content
 首页 » 编程设计

python之header If-Modified-Since 不给出 304 代码

2025年05月04日10mayingbao

我正在使用下面的代码保存一个 html 文件,其名称中带有时间戳:

import contextlib 
import datetime 
import urllib2 
import lxml.html 
import os 
import os.path 
timestamp='' 
filename='' 
for dirs, subdirs, files in os.walk("/home/test/Desktop/"): 
    for f in files: 
        if "_timestampedfile.html" in f.lower(): 
            timestamp=f.split('_')[0] 
            filename=f 
            break 
if timestamp is '':  
    timestamp=datetime.datetime.now() 
 
with contextlib.closing(urllib2.urlopen(urllib2.Request( 
        "http://www.google.com", 
        headers={"If-Modified-Since": timestamp}))) as u: 
    if u.getcode() != 304: 
        myfile="/home/test/Desktop/"+str(datetime.datetime.now())+"_timestampedfile.html" 
        file(myfile, "w").write(urllib2.urlopen("http://www.google.com").read()) 
        if os.path.isfile("/home/test/Desktop/"+filename): 
        os.remove("/home/test/Desktop/"+filename) 
        html = lxml.html.parse(myfile) 
    else: 
        html = lxml.html.parse("/home/test/Desktop/"+timestamp+"_timestampedfile.html") 
 
links=html.xpath("//a/@href") 
print u.getcode() 

当我每次从 If-Modified-since header 获取代码 200 时运行此代码。我哪里做错了?我的目标是保存和使用一个 html 文件,如果它在上次访问后被修改,html 文件应该被覆盖。

请您参考如下方法:

问题是 If-Modified-Since 是 supposed to be一个formatted日期字符串:

If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT 

但是您传递的是日期时间元组。

尝试这样的事情:

timestamp = time.time() 
... 
time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(timestamp)) 

您的代码未按预期工作的第二个原因:

http://www.google.com/似乎不遵守 If-modified-since。 RFC 允许这样做,他们可能出于各种原因选择该行为。

  c) If the variant has not been modified since a valid If- 
     Modified-Since date, the server SHOULD return a 304 (Not 
     Modified) response. 

如果你尝试 http://www.stackoverflow.com/ ,例如,你会看到一个 304。(我刚刚试过了。)