2

我正在使用下面的代码来保存一个名称中带有时间戳的 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 标头中获取代码 200 时运行此代码时。我在哪里做错了?我的目标是保存和使用一个 html 文件,如果它在上次访问后被修改,则应该覆盖 html 文件。

4

1 回答 1

11

问题是If-Modified-Since应该格式化日期字符串:

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。(我刚刚尝试过。)

于 2013-07-24T23:11:55.557 回答