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文件應該被覆蓋。
現在我使用datetime.datetime.now()的ctime( )這是給我這種格式的時間Wed Jul 24 16:16:19 2013,仍然沒有工作。有什麼方法可以按照您所建議的格式獲得時間? – user2460869
['ctime'輸出]也不是正確的格式。它必須格式化爲「Sat,1994年10月29日19:43:31 GMT」。我已經更新了我的答案,以包含一些生成符合值的示例代碼。希望有所幫助! –
仍然沒有工作,現在我給這種格式的時間星期三,24七月2013 23:37:11 GMT – user2460869