元素的xpath一直在變化,如何在Selenium中找到這個元素的動態xpath?


我們可以藉助xpath函式來查詢屬性值或文字不斷變化的元素的xpath。它們有助於識別具有動態屬性值或文字的元素。下面列出了一些這樣的函式:

  • text() – 透過頁面上可見的文字識別元素。元素“首頁”的xpath表示式為 //*[text()='Home']。

  • starts-with – 識別屬性值以特定文字開頭的元素。此函式通常用於本質上是動態的屬性值。

    “首頁”的xpath表示式為 //a[starts-with(@title, 'Questions &')].

  • contains - 識別屬性值包含實際屬性值子文字的元素。此函式通常用於本質上是動態的屬性值。

    “首頁”的xpath表示式 //a[contains(@title, 'Questions & Answers')].

我們還可以藉助具有以下格式的單個或多個屬性建立動態xpath:

//tagname[@attribute='value'] – with one attribute
//tagname[@attribute1='value'][@attribute2='value'] – with more than one attributes.

語法

//img[@alt='Tutorialspoint']

語法

//img[@alt='Tutorialspoint'] [@title='Tutorialspoint']

我們還可以藉助屬性上的OR和AND操作建立動態xpath,其格式如下:

//tagname[@attribute1='value' or @attribute2='value']
//tagname[@attribute1='value' and @attribute2='value']

語法

//img[@alt='Tutorialspoint' or @name='Tutorial']
//img[@alt='Tutorialspoint' and @id='txt']

更新於: 2021年4月6日

2K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告