編集:私はあなたがあなたのスクリプトの問題を探しているだけだとは気づいていませんでした。これが私が問題だと思うものであり、その後にあなたが解決しようとしているより大きな問題への別のアプローチに対処する私の元の答えが続きます。
スクリプトは、包括的な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:特定のURLに適合。
そのページの広告には動的に生成される番号があり、ページが読み込まれるたびに変化します。すべてのコンテンツの終わり近くにあるので、その時点で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
、コンテンツが変更されたかどうかを確認するために使用できるプロパティを指定します(サーバーが真実を伝えていると仮定します)。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().
"""
また、いくつかのインスピレーションを提供する可能性のあるStiiによるこのブログ投稿もチェックしてください。それらを私の例に入れるのに十分なことはわかりませんETags
が、彼のコードはそれらもチェックします。