【问题标题】:Making Absolute XPath more robust for testing使 Absolute XPath 对测试更加健壮
【发布时间】:2021-07-27 10:21:01
【问题描述】:

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

在互联网挑战 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' and text()='foo']
  • 这应该适用于您的情况//a[contains(@class, 'button') and position() = 1]。另外position() = 1会选择第一个按钮,你可以根据你要点击的来改变值。

标签: python selenium testing pytest


【解决方案1】:

看到蓝色按钮有这个 HTML

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

很明显,id 正在生成 dynamically

href没有有任何value

classbuttontextbar(但文字会不断变化,因此我们也不会考虑文字

所以基于类,我们可以构造一个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
    

【讨论】:

    【解决方案2】:

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

    //a[@class='button']
    

    【讨论】:

      【解决方案3】:

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

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

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

      //a[@class='button']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-10
        • 2011-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多