首页 > 解决方案 > Python Selenium 动态条件

问题描述

我正在使用 selenium 进行自动化,但找不到元素。我真的认为这是因为动态元素。有时它会显示“您找到 0”或“您找到 1”。这是html代码 图像 这是我现在关于它的代码

ele = driver.find_element_by_xpath("//*[@class='swal-text' and (contains(text(),'You found 4'))]").is_displayed()
if (ele):
    print("4 ")
else:
    pass

错误说如果没有找到,你们能帮帮我吗,请 Python 3.9.0

标签: pythonseleniumif-statementautomation

解决方案


我会建议一个更好的 xpath,例如//div[@class='swal-modal']/div[@class='swal-text']初学者。

问题是您的包含过于严格。即使这样会“更好”:ele = driver.find_element_by_xpath("//*[@class='swal-text' and (contains(text(),'You found '))]").is_displayed()

如果您可以以编程方式确定预期的数量,您可以像任何其他字符串连接一样注入它:

expected_value = 4
ele = driver.find_element_by_xpath("//*[@class='swal-text' and (contains(text(),'You found " + expected_value + "'))]").is_displayed()

推荐阅读