动态条件

2024-10-01 00:31:29 发布

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

我正在使用selenium实现自动化,但我在查找元素时遇到了困难。我真的认为这是因为动态元素。有时它会显示“您找到0”或“您找到1”。 下面是html代码 image 这是我现在的代码

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


Tags: 代码textimage元素byhtmldriverselenium
2条回答

我建议初学者使用更好的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()

您是否尝试过按类名查找元素? 在你的情况下,那就是

ele = driver.find_element_by_class_name('swal-text')

相关问题 更多 >