Webdriver 中部分 link 文本的可行定位器策略

Viable locator strategies for partial link text in webdriver

我正在测试一个消息传递应用程序,我打算让代码等待它收到消息“你好,我叫 Jeff”。

我尝试了 2 条失败的代码:

msg_receive_1 = WebDriverWait(driver1, 15).until(
        EC.visibility_of_element_located((By.PARTIAL_LINK_TEXT, "Hello"))
    )
msg_receive_1 = WebDriverWait(driver1, 15).until(
        EC.visibility_of_element_located((By.LINK_TEXT, "Hello, my name is Jeff."))
    )

元素的可见性是否是部分 link 文本的低于标准的选择?如果是这样,什么是可行的替代方案?

如果是其他问题,那可能是什么?

您应该使用 XPath,而不是 Link 文本。
试试这个:

msg_receive_1 = WebDriverWait(driver1, 15).until(
    EC.visibility_of_element_located((By.XPATH, "//*[contains(text(),'Hello')]"))
)

或者这个:

msg_receive_1 = WebDriverWait(driver1, 15).until(
    EC.visibility_of_element_located((By.XPATH, "//*[contains(text(),'Hello, my name is Jeff')]"))
)

如果你确定是文本字符串,也可以是这样的:

msg_receive_1 = WebDriverWait(driver1, 15).until(
    EC.visibility_of_element_located((By.XPATH, "//*[text()='Hello, my name is Jeff.']"))
)

你的问题

Is visibility of element located a sub-par choice for partial link text?

没有,绝对没有。

查看visibility_of_element_located方法下面的内容:-

""" An expectation for checking that an element is present on the DOM of a
page and visible. Visibility means that the element is not only displayed
but also has a height and width that is greater than 0.
locator - used to find the element
returns the WebElement once it is located and visible
"""
class visibility_of_element_located(object):
    def __init__(self, locator):
        self.locator = locator

    def __call__(self, driver):
        try:
            return _element_if_visible(_find_element(driver, self.locator))
        except StaleElementReferenceException:
            return False

所以基本上它会调用,

_element_if_visible

这就是我们所拥有的

def _element_if_visible(element, visibility=True):
    return element if element.is_displayed() == visibility else False

因此,您的问题的直接答案是否定的。但这取决于您如何定义 EC,在您的情况下,您确定那是唯一的 link_text 还是 partial_link_text, 您是否尝试将其更改为 css 或 xpath 并如下验证?

//*[contains(text(),'Hello')]

在代码中:

msg_receive_1 = WebDriverWait(driver1, 15).until(
        EC.visibility_of_element_located((By.XPATH, "//*[contains(text(),'Hello')]"))
    )

作为 xpath ?