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))

コードが期待どおりに機能しない 2 つ目の理由:

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 に答える