简体   繁体   English

Python Selenium 动态条件

[英]Python Selenium dynamic condition

I'm doing automation with selenium but I'm having trouble finding an element.我正在使用 selenium 进行自动化,但我无法找到元素。 I really thought this is because dynamic elements.我真的认为这是因为动态元素。 Sometimes it displays "You found 0" or "You found 1".有时它会显示“您找到 0”或“您找到 1”。 Here is the html code image Here is my code right now about it这是 html 代码图像这是我现在的代码

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

The error says if it's not found, can you help me guys, please Python 3.9.0错误说如果找不到,你能帮我吗,请 Python 3.9.0

Have you tried finding the element by class name?您是否尝试过按类名查找元素? In your case that would be在你的情况下,这将是

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

I would suggest a better xpath such as //div[@class='swal-modal']/div[@class='swal-text'] for starters.对于初学者,我建议使用更好的 xpath,例如//div[@class='swal-modal']/div[@class='swal-text']

the problem is your contains is overly strict.问题是您的包含过于严格。 Even this would be "better": ele = driver.find_element_by_xpath("//*[@class='swal-text' and (contains(text(),'You found '))]").is_displayed()即使这样也会“更好”: ele = driver.find_element_by_xpath("//*[@class='swal-text' and (contains(text(),'You found '))]").is_displayed()

If you could programatically determine the number expected you could inject that like any other string concatinations:如果您可以以编程方式确定预期的数字,则可以像任何其他字符串连接一样注入它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM