selenium Class name and value selection in xpath

愈來愈常見到這種寫法,常遇到 <button> 的 tag, 要判斷有沒有 class 屬性裡有沒有 “selected” 這一個值。

解法1:

driver.find_elements(By.XPATH, '//button[contains(@class, "selected")]')

解法2: 把 element 的 attribute 取出來判斷。

button_cass = str(el_time_picker.get_attribute('class'))
if "selected" in button_cass:

This selector should work but will be more efficient if you replace it with your suited markup:

//*[contains(@class, 'Test')]

Or, since we know the sought element is a div:

//div[contains(@class, 'Test')]

But since this will also match cases like class="Testvalue" or class="newTest", @Tomalak’s version provided in the comments is better:

//div[contains(concat(' ', @class, ' '), ' Test ')]

If you wished to be really certain that it will match correctly, you could also use the normalize-space function to clean up stray whitespace characters around the class name (as mentioned by @Terry):

//div[contains(concat(' ', normalize-space(@class), ' '), ' Test ')]

Note that in all these versions, the * should best be replaced by whatever element name you actually wish to match, unless you wish to search each and every element in the document for the given condition.

說明:之所以要寫這麼複雜,是因為 1foo, foo, foo2, 如果只有使用 contains ‘foo’ 這3個都會被選到,預期只想選 ‘foo’ 的話要寫的複雜才能取得。


資料來源

How can I find an element by CSS class with XPath?
https://stackoverflow.com/questions/1604471/how-can-i-find-an-element-by-css-class-with-xpath

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *