使用 Selenium Python 处理甜蜜警报 2 通知

时间:2021-05-25 03:21:58

标签: python python-3.x selenium

我需要找到sweet alert的文字内容,看html:

<div id="swal2-content" class="swal2-html-container" style="display: block;">Success</div>

但即使等待或“睡觉”我也找不到内容! 我的代码是这样的:

wd.implicitly_wait(30)
message = wd.find_element_by_id("swal2-content").text
print(message)
if message == 'Success':
  time.sleep(180)
else:
  print(wd.find_element_by_id("swal2-content"))
  break

1 个答案:

答案 0 :(得分:0)

此处必须使用 implicitly_wait 而不是 expected conditions

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

message  = WebDriverWait(wd, 20).until(EC.visibility_of_element_located((By.ID, "swal2-content"))).text

因为当元素出现在页面上时,implicitly_wait 会立即完成,但该元素在那一刻仍未完成渲染。所以元素的文本仍然不存在。这就是为什么您的预期文本 Success 仍然不存在的原因。