编辑:我没有意识到您只是在寻找脚本的问题。这就是我认为的问题,然后是我的原始答案,它解决了您要解决的更大问题的另一种方法。
您的脚本是使用毯子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 文档。如果是这样,您可能会删除该行或其他内容。可能有一种更优雅的方式来做到这一点——也许用正则表达式删除数字——但这至少可以满足你的问题。
原始答案——解决问题的另一种方法。
来自网络服务器的响应标头是什么样的? HTTP 指定了一个Last-Modified 属性,您可以使用它来检查内容是否已更改(假设服务器说的是真话)。正如 Uku 在他的回答中显示的那样,将此与 HEAD 请求一起使用。如果您想节省带宽并对正在轮询的服务器友好。
还有一个 If-Modified-Since 标头,听起来像您可能正在寻找的。p>
如果我们把它们结合起来,你可能会想出这样的东西:
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 的了解不够,无法将它们放在我的示例中,但他的代码也会检查它们。