【问题标题】:Why is my selenium expected condition not working as the condition in the python if statement?为什么我的硒预期条件不能作为 python if 语句中的条件工作?
【发布时间】:2021-08-13 18:52:21
【问题描述】:

我在下面有一个功能,可以点击我页面上表单上的提交按钮。为了成功提交表格,必须附上文件。但是,有时根据数据库的链接方式,保存的文档不会填充为已上传。

这是一个小细节,优先提交表单。我创建了一个 if 语句来检查上传按钮是否存在。如果是,那么它应该从我的电脑上传一个文件,然后单击提交按钮。如果不是,那么它应该只是单击提交按钮。

当存在上传按钮时,此方法有效。但是,当它不是时,它会卡在 if 条件上并且不会到达 else 子句。


def submit_draw_request(driver, document_file_path):
    if EC.visibility_of_element_located((By.XPATH, "//button[text()='Upload']")):
        shared.upload_file_from_computer(driver, "//input[@class='MultipleFileUploadWidget']", document_file_path)
        time.sleep(2)
        shared.click_button(driver, elements.submit_button)
    else:
        time.sleep(2)
        shared.click_button(driver, elements.submit_button)

【问题讨论】:

标签: python selenium if-statement expected-condition


【解决方案1】:

您可以尝试在 python 中使用try-except 块。在使用 WebDriverWaitexpected_conditions 时还需要进行一些导入

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
try:
    wait.until(EC.visibility_of_element_located((By.XPATH, "//button[text()='Upload']")))
    shared.upload_file_from_computer(driver, "//input[@class='MultipleFileUploadWidget']", document_file_path)
    time.sleep(2)
    shared.click_button(driver, elements.submit_button)       

except:
    time.sleep(2)
    shared.click_button(driver, elements.submit_button)

try 块可让您测试代码块是否有错误。
except 块可让您处理错误。
finally 块允许您执行代码,而不管 try- 和 except 块的结果。

【讨论】:

    【解决方案2】:

    您似乎缺少定义预期条件超时。
    所以应该是这样的:

    wait = WebDriverWait(driver, 10)
    def submit_draw_request(driver, document_file_path):
        if wait.until(EC.visibility_of_element_located((By.XPATH, "//button[text()='Upload']"))):
            shared.upload_file_from_computer(driver, "//input[@class='MultipleFileUploadWidget']", document_file_path)
            time.sleep(2)
            shared.click_button(driver, elements.submit_button)
        else:
            time.sleep(2)
            shared.click_button(driver, elements.submit_button)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      • 2016-07-24
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多