編輯:我沒有意識到你只是在尋找與你的腳本的問題。這就是我認爲的問題,其次是我的原始答案,它解決了您嘗試解決更大問題的另一種方法。
你的腳本是使用毯子except
聲明的危險的一個很好的例子:你抓住了一切。其中包括您的sys.exit(0)
。
我假設你是try
區塊是否存在D:\Download\htmlString.p
尚不存在的情況。該錯誤被稱爲IOError
,你可以用except IOError:
這是你的腳本加上一點讓它走之前代碼專門捕獲它,固定你的except
問題:
import sys
import pickle
import urllib2
request = urllib2.Request('http://www.iana.org/domains/example/')
response = urllib2.urlopen(request) # Make the request
htmlString = response.read()
try:
file = pickle.load(open('D:\\Download\\htmlString.p', 'rb'))
if file == htmlString:
print("Values haven't changed!")
sys.exit(0)
else:
pickle.dump(htmlString, open('D:\\Download\\htmlString.p', "wb"))
print('Saving')
except IOError:
pickle.dump(htmlString, open('D:\\Download\\htmlString.p', "wb"))
print('Created new file.')
作爲一個側面說明,您可以考慮使用os.path
作爲您的文件路徑 - 它可以幫助以後任何人想要在其他平臺上使用您的腳本,並且可以爲您節省難看的雙反斜槓。
編輯2:改編爲您的特定網址。
該頁面上的廣告有一個動態生成的編號,隨每個頁面加載而變化。在完成所有內容之後,它接近尾聲,所以我們可以在此時分割HTML字符串,並取前半部分,丟棄具有動態數字的部分。
import sys
import pickle
import urllib2
request = urllib2.Request('http://ecal.forexpros.com/e_cal.php?duration=weekly')
response = urllib2.urlopen(request) # Make the request
# Grab everything before the dynabic double-click link
htmlString = response.read().split('<iframe src="http://fls.doubleclick')[0]
try:
file = pickle.load(open('D:\\Download\\htmlString.p', 'r'))
if pickle.load(open('D:\\Download\\htmlString.p', 'r')) == htmlString:
print("Values haven't changed!")
sys.exit(0)
else:
pickle.dump(htmlString, open('D:\\Download\\htmlString.p', "w"))
print('Saving')
except IOError:
pickle.dump(htmlString, open('D:\\Download\\htmlString.p', "w"))
print('Created new file.')
你的字符串不是有效的HTML文檔了,如果這是非常重要的。如果是這樣,你可能只是刪除該行或其他東西。這可能是一種更優雅的方式,可能會用正則表達式刪除數字 - 但這至少可以滿足您的問題。
原答覆 - 解決問題的替代方法。
Web服務器的響應頭文件是什麼樣的? HTTP指定了一個Last-Modified
屬性,您可以使用該屬性來檢查內容是否已更改(假設服務器說實話)。在Uku在他的回答中顯示的請求中使用這個請求,請求HEAD
。如果你想節省帶寬並且對你所投票的服務器很好。
還有一個If-Modified-Since
標題,這聽起來像你可能要找的東西。
如果我們將它們組合起來,你可能會想出這樣的事情:
import sys
import os.path
import urllib2
url = 'http://www.iana.org/domains/example/'
saved_time_file = 'last time check.txt'
request = urllib2.Request(url)
if os.path.exists(saved_time_file):
""" If we've previously stored a time, get it and add it to the request"""
last_time = open(saved_time_file, 'r').read()
request.add_header("If-Modified-Since", last_time)
try:
response = urllib2.urlopen(request) # Make the request
except urllib2.HTTPError, err:
if err.code == 304:
print "Nothing new."
sys.exit(0)
raise # some other http error (like 404 not found etc); re-raise it.
last_modified = response.info().get('Last-Modified', False)
if last_modified:
open(saved_time_file, 'w').write(last_modified)
else:
print("Server did not provide a last-modified property. Continuing...")
"""
Alternately, you could save the current time in HTTP-date format here:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
This might work for some servers that don't provide Last-Modified, but do
respect If-Modified-Since.
"""
"""
You should get here if the server won't confirm the content is old.
Hopefully, that means it's new.
HTML should be in response.read().
"""
而且check out this blog post由STII可以提供一些啓示。我不太瞭解ETags
將它們放入我的示例中,但他的代碼也會檢查它們。
遠程和本地內容的內容/ mimetype是什麼? – DeaconDesperado
保存和比較整個頁面將會非常低效。你可以計算一個像md5這樣的散列並保存。如果將來哈希匹配,那麼頁面沒有改變。 – TJD
我已更新我的答案以解決您的編輯問題。那是你在找什麼? – Phil