你要等到什么时候?

2024-09-30 04:40:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从以前请求的url获取数据。到目前为止一切正常

我的问题是: 我尝试每X秒进行一次查询,如果查询显示不同的值,则应该执行一些操作。但即使在最终响应返回时也会打印解决捕获!=未准备好

 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...")

Tags: keyhttpscomjsonurlgetresaction
1条回答
网友
1楼 · 发布于 2024-09-30 04:40:07

这是因为你写代码的方式, 假设最终回复尚未准备就绪,则会发生以下情况:

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

此代码不好,因为如果它更改为not be 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"

这是因为它已经是一个字符串值(由语音标记“”指示)

相关问题 更多 >

    热门问题