Python、selenium - 如何刷新页面直到找到项目?

Python, selenium - how to refresh page until item found?

我正在尝试刷新页面直到项目出现,但我的代码不起作用(我采用了模式:python selenium keep refreshing until item found (Chromedriver))。

代码如下:

while True:
    try:
        for h1 in driver.find_elements_by_class_name("name-link"):
            text = h1.text.replace('\uFEFF', "")
            if "Puffy" in text:
                break
    except NoSuchElementException:
        driver.refresh
    else:
        for h1 in driver.find_elements_by_class_name("name-link"):
            text = h1.text.replace('\uFEFF', "")
            if "Puffy" in text:
                h1.click()
                break
        break

这些片段是因为我必须找到一个具有相同 class 名称的项目并将 BOM 替换为“”(find_element_by_partial_link_text 无效)。

for h1 in driver.find_elements_by_class_name("name-link"):
    text = h1.text.replace('\uFEFF', "")
    if "Puffy" in text:
        break

有人可以帮助我吗?非常感谢。

您正在尝试获取元素列表(driver.find_elements_by_class_name() 可能 return 元素列表或空列表 - 无一例外)- 在这种情况下您无法获取 NoSuchElementException,所以driver.refresh不会被执行。试试下面的方法

while True:
    if any(["Puffy" in h1.text.replace('\uFEFF', "") for h1 in driver.find_elements_by_class_name("name-link")]):
        break
    else:
        driver.refresh
driver.find_element_by_xpath("//*[contains(., 'Puffy')]").click()