2013-07-24 27 views
1

我使用下面的代碼保存爲HTML文件名稱中帶有時間戳:頭如果-Modified-Since的不給304碼

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文件應該被覆蓋。

回答

5

的問題是,If-Modified-Sincesupposed 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(我只是嘗試它。)

+0

現在我使用datetime.datetime.now()的ctime( )這是給我這種格式的時間Wed Jul 24 16:16:19 2013,仍然沒有工作。有什麼方法可以按照您所建議的格式獲得時間? – user2460869

+0

['ctime'輸出]也不是正確的格式。它必須格式化爲「Sat,1994年10月29日19:43:31 GMT」。我已經更新了我的答案,以包含一些生成符合值的示例代碼。希望有所幫助! –

+0

仍然沒有工作,現在我給這種格式的時間星期三,24七月2013 23:37:11 GMT – user2460869