使 Absolute XPath 更适合测试

Making Absolute XPath more robust for testing

我是测试自动化领域的新手,一直在自学。

在互联网挑战 DOM 页面上,我使用绝对 Xpath 找到了蓝色按钮,这是我唯一能想到的。当页面刷新时,其他所有选择器似乎都在动态变化。

在这种情况下,有没有办法让这个选择更加稳健?从谷歌搜索来看,这似乎是一种在网页上定位内容的脆弱方法。

https://the-internet.herokuapp.com/challenging_dom

''' #Test blue button on page, repeated 5 times and text displayed checked against options. 
@pytest.mark.repeat(5)
def test_2():
    elem1 = b.find_element(By.XPATH, 'html/body/div[2]/div/div/div/div/div[1]/a[1]')
    a=(elem1.text)`enter code here`
    elem1.click()
    assert a in Names
    print (a)'''

此元素的正确且唯一的 XPath 可以是

//a[@class='button']

看到蓝色按钮有这个HTML

<a id="240aa520-d0f5-0139-b953-067df9ace5fa" href="" class="button">bar</a>

很明显 id 正在生成 dynamically

href没有有任何value.

classbuttontextbar(但是文字一直在变化所以我们 不会考虑文字 还有)

所以在class的基础上,我们可以构造一个xpath

//a[@class='button']

现在的问题是我们在 DOM 中有多个条目,对吗?

所以在这种情况下,我们有 2 个选项:-

  1. Xpath index
  2. find_elements

使用 xpath 索引:

第一个按钮:-

 (//a[@class='button'])[1]   

第二个按钮:-

 (//a[@class='button'])[2]

等等..

  1. 使用find_elements:

     buttons = driver.find_elements(By.XPATH, "//a[@class='button']")
    
     buttons[0].click()  # to click on first button
    
     buttons[1].click()  # to click on second button
    

由于三按钮具有动态 id 值,所以我只是尝试检查 id 的静态部分,这对所有按钮都是通用的,我们根据索引获得了所需的按钮。

((//a[contains(@id,'067df9ace5fa')])[1])

按钮的文本正在更改,但属性保持不变,因此您可以在下方查看

//a[@class='button']