[英]Python wait until?
我正在从先前请求的 url 获取数据。 到目前为止一切正常。
我的问题:我尝试每 X 秒进行一次查询,如果查询显示不同的值,则应该执行某些操作。 但即使在 finalresponseback != notready 时它也会打印 Solving-Capture
responseback = requests.get('https://2captcha.com/res.php?json=1&action=get&key=' + apikey + "&id=" + finalrequest)
responseback_json = responseback.json()
finalresponseback = responseback_json['request']
print(responseback_json)
notready = (str("CAPCHA_NOT_READY"))
while(finalresponseback == notready):
print("Solving-Capture...")
if finalresponseback != notready:
print("Entering...")
这是因为您编写代码的方式,假设 finalresponseback 还没有准备好,那么会发生这种情况:
while(finalresponseback == notready): # This would enable the loop because it's equal to not ready
print("Solving-Capture...") # It would print this
if finalresponseback != notready: # Nothing would happen because it is equal to notready
print("Entering...") # This woudln't happen
但是,如果突然发生变化:
while(finalresponseback == notready): # This happened before it changed
print("Solving-Capture...") # This also happened before it changed, so it happens anyway
if finalresponseback != notready: # This happens too
print("Entering...") # And so does this, so therefore it would print both statements
这段代码很糟糕,因为如果它更改为 notready,那么它将退出循环而不做任何事情,除非它在循环中发生更改,一个更好的版本是:
while(1): # Starts a loop
if finalresponseback != notready: # Checks finalresponseback
print("Entering...") # Prints statement
break # Exits loop
else: # If it is equal to notready
print("Solving-Capture...") # Print statement
上面的代码直接检查循环中的 finalresponseback,因此,它将能够打印语句,而不是像以前一样在开始时完全退出。
最后,我们可以添加:
responseback_json = responseback.json()
finalresponseback = responseback_json['request']
到代码以每 x 秒请求一次:
import time # Add to top of code, imports the time library
x = 2 # Sets the x variable
while(1): # Starts a loop
responseback_json = responseback.json()
finalresponseback = responseback_json['request']
if finalresponseback != notready: # Checks finalresponseback
print("Entering...") # Prints statement
break # Exits loop
else: # If it is equal to notready
print("Solving-Capture...") # Print statement
time.sleep(x)
最后,一个优化代码的技巧,而不是
notready = (str("CAPCHA_NOT_READY"))
你可以做
notready = "CAPCHA_NOT_READY"
这是因为它已经是一个字符串值(如语音标记“”所示)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.