gpt4 book ai didi

python - 如何检查网站上的值是否已更改

转载 作者:太空狗 更新时间:2023-10-29 22:13:52 26 4
gpt4 key购买 nike

基本上,如果网站上的值发生变化,我会尝试运行一些代码 (Python 3.2),否则稍等片刻,稍后再检查。

首先,我认为我可以将值保存在一个变量中,并将其与下次脚本运行时获取的新值进行比较。但这很快就遇到了问题,因为当脚本再次运行并初始化该变量时,该值被覆盖了。

然后我尝试将网页的 html 保存为文件,然后将其与下次脚本运行时调用的 html 进行比较。那里也不走运,因为即使没有任何变化,它也会不断出现 False。

接下来是 pickle 网页,然后尝试将其与 html 进行比较。有趣的是,这在脚本中也不起作用。但是,如果我在脚本运行后键入 file = pickle.load( open( 'D:\Download\htmlString.p', 'rb')) 然后 file == html,当没有任何变化。

我有点困惑为什么它在脚本运行时不起作用,但如果我执行上述操作,它会显示正确答案。

编辑:感谢大家到目前为止的回复。我的问题并不是关于其他方法来解决这个问题(尽管学习更多方法来完成任务总是好的!)而是为什么下面的代码在作为脚本运行时不起作用,但是如果我脚本运行后在提示符处重新加载 pickle 对象,然后根据 html 对其进行测试,如果没有任何更改,它将返回 True。

try: 
file = pickle.load( open( 'D:\\Download\\htmlString.p', 'rb'))
if pickle.load( open( 'D:\\Download\\htmlString.p', 'rb')) == htmlString:
print("Values haven't changed!")
sys.exit(0)
else:
pickle.dump( htmlString, open( 'D:\\Download\\htmlString.p', "wb" ) )
print('Saving')
except:
pickle.dump( htmlString, open( 'D:\\Download\\htmlString.p', "wb" ) )
print('ERROR')

最佳答案

编辑:我没有意识到您只是在寻找脚本的问题。这是我认为的问题所在,然后是我的原始答案,它解决了您要解决的更大问题的另一种方法。

您的脚本是使用一揽子 except 语句的危险的一个很好的例子:您捕获了一切。在这种情况下,包括您的 sys.exit(0)

我假设您正在使用 try block 来捕获 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 服务器的响应 header 是什么样的? 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 了解不够,无法将它们放在我的示例中,但他的代码也会检查它们。

关于python - 如何检查网站上的值是否已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11252576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com