【问题标题】:exit python script when no match in for loop当 for 循环中不匹配时退出 python 脚本
【发布时间】:2022-01-22 20:11:41
【问题描述】:

使用 python 中的 selenium,如果它包含一些单词并且找不到任何脚本必须退出,我想单击 html div 容器。 使用下面的代码,如果有一个 div 包含来自text 列表的单词,但我如何退出没有找到单词的地方?使用下面的代码,它会执行order.click,因为这是在 for 循环之外。我只想执行order.click(),如果找到的话,继续使用脚本的其余部分break

    text = ["Dog", "Cat", "Bird"]

    for word in text:
        try:
            order = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, "//div/p[contains(text(),'{}')]".format(word))))
            if order != None:
                print(f"found div with word: {word}")
                break
        except:
            print(f"did NOT found div with word: {word}")

    order.click()
 
  # and more commands after this....

【问题讨论】:

    标签: python python-3.x for-loop selenium-webdriver


    【解决方案1】:
    import sys
    

    并且在除了:

        text = ["Dog", "Cat", "Bird"]
        is_found = False
        for word in text:
            try:
                order = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, "//div/p[contains(text(),'{}')]".format(word))))
                if order != None:
                    print(f"found div with word: {word}")
                    is_found = True
                    break
            except:
                print(f"did NOT found div with word: {word}")
    
        if is_found == False:
            sys.exit()
        order.click()
     
      # and more commands after this....
    

    如果你想退出整个脚本。

    如果你只是不想运行order.click(), 然后将此行移动到您的try 范围内:

    try:
                order = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, "//div/p[contains(text(),'{}')]".format(word))))
                if order != None:
                    print(f"found div with word: {word}")
                    order.click()
                    break
    

    【讨论】:

    • 谢谢,但现在脚本将在第一个未找到时立即关闭,而无需检查其他两个。它所要做的就是只有在没有找到任何单词时才关闭脚本。它必须执行 order.click 例如如果找到 Bird 但没有包含 Dog 或 Cat 的 div
    • 有你的问题,刚刚编辑了答案。
    • 是的,非常感谢!这样就可以了:)
    【解决方案2】:

    我认为您需要在代码的缩进部分中包含“order.click()”,以检查是否在列表中找到该项目,如下所示。

    text = ["Dog", "Cat", "Bird"]
    
    for word in text:
        try:
            order = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, "//div/p[contains(text(),'{}')]".format(word))))
            if order != None:
                print(f"found div with word: {word}")
                order.click()
                break
        except:
            print(f"did NOT found div with word: {word}")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 1970-01-01
      • 2015-02-01
      相关资源
      最近更新 更多