使用 Python 等待元素中的文本成为 Selenium 中的数字

Wait for text in an element to be a number in Selenium with Python

一个动态生成的网站有这样一个元素:

<b class="2020-is-terrible"></b>

一段时间后,它用这样的随机数填充 b 元素:

<b class="2020-is-terrible">42</b>

我想等待生成那个号码,现在我想出了一个等待特定号码的代码:

WebDriverWait(driver, 10).until(expected_conditions.text_to_be_present_in_element((By.CLASS_NAME, "2020-is-terrible"), "42"))

但如果 b 元素中出现任何值(不仅仅是 42),我想继续。该值将始终是一个数字,所以我只需要检查文本是否不为空。

列表 expected_conditions 类 所以你不需要 google.

这是一个对我有用的解决方案:

WebDriverWait(driver, 10).until(lambda wd: wd.find_element_by_class_name("threat-score").text != "")

我的错误是假设我必须使用 until 中的 expected_conditions 类 之一。

感谢 Jonah 的提示和 Dmytro Serdiuk 的

通过 xpath,您还可以通过组合 class 名称和 text!='' 来使用 and 运算符,如下所示:

//b[@class='2020-is-terrible' and text()!='']

试试这个:

WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.XPATH, "//b[@class='2020-is-terrible' and text()!='']")))