편집는 : 나는 당신이 당신의 스크립트의 문제를 찾고 있었다 실현하지 않았다. 여기 내가 문제라고 생각하는 것, 해결하려고하는 더 큰 문제에 대한 또 다른 접근법을 다루는 본래의 대답이 뒤 따릅니다.
귀하의 스크립트는 담요 except
문을 사용하는 위험의 좋은 예입니다. 모든 것을 잡습니다. 이 경우에는 sys.exit(0)
을 포함합니다.
나는 D:\Download\htmlString.p
이 아직 존재하지 않는 경우를 잡기 위해 블록이 try
이라고 가정합니다. 보조 노트로
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.')
: 그 오류가 IOError
라고, 당신은 여기에 except IOError:
스크립트 플러스가 갈 수 있도록하기 전에 코드의 비트가 구체적으로 그것을 잡을 수있는, 당신의 except
문제에 대한 해결 파일 경로에 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 문서 입니다. 만약 그렇다면, 당신은 그 라인이나 뭔가를 제거 할 수 있습니다. 아마도 이것을하는 더 우아한 방법이있을 것입니다 - 아마도 정규 표현식으로 숫자를 지우는 것입니다 -하지만 이것은 적어도 당신의 질문을 만족시킵니다.
Original Answer - 문제에 대한 대체 접근 방식.
웹 서버의 응답 헤더는 어떻게됩니까? HTTP는 내용이 변경되었는지 확인하는 데 사용할 수있는 Last-Modified
속성을 지정합니다 (서버가 사실을 알리는 경우). Uku가 대답 한 것처럼 HEAD
요청을 사용하십시오. 대역폭을 절약하고 폴링하려는 서버에 좋을 수 있습니다.
그리고 If-Modified-Since
헤더가있을 수 있습니다.
우리가 그들을 결합 할 경우,이 같은 것을 가지고 올 수 있습니다 STII에 의해
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하는 영감을 제공 할 수있다. 내 예제에 넣기에는 ETags
에 대해 충분히 알지 못하지만 코드는이를 확인합니다.
원격 및 로컬 콘텐츠의 내용/MIME 형식은 무엇입니까? – DeaconDesperado
전체 페이지를 저장하고 비교하는 것은 매우 비효율적입니다. md5와 같은 해시를 계산하고 저장할 수 있습니다. 해시가 나중에 일치하면 페이지가 변경되지 않았습니다. – TJD
수정 사항을 해결하기 위해 답변을 업데이트했습니다. 그게 니가 찾고 있던거야? – Phil