HTML XPath Searching by class and text

和自甴很熟 提交于 2020-08-22 07:11:02

问题


I want to find all elements in xpath by class and text. I have tried this but it does not work.

//*[contains(@class, 'myclass')]//*[text() = 'qwerty']

I am trying to find all elements that have a class of 'myclass' and the text is 'qwert' (these will be span elements)


回答1:


//span[contains(@class, 'myclass') and text() = 'qwerty']

or

//span[contains(@class, 'myclass') and normalize-space(text()) = 'qwerty']



回答2:


Generic solution for anyone looking for a XPath expression to search based on class and text:

Class is only "myclass":

//*[@class='myclass' and contains(text(),'qwerty')]

Class contains "myclass":

//*[contains(@class,'myclass') and contains(text(),'qwerty')]



回答3:


Presuming the conditions below:

  • The class attribute contains only myclass
  • The innerText contains qwerty (without any leading and trailing spaces)

You can use the following solution:

//*[@class='myclass' and text()='qwerty']

Incase the innerText contains qwerty along with some leading and trailing spaces, you can use either of the following solutions:

  • Using normalize-space():

    //*[@class='myclass' and normalize-space()='qwerty']
    
  • Using contains():

    //*[@class='myclass' and contains(., 'qwerty')]
    


来源:https://stackoverflow.com/questions/16466083/html-xpath-searching-by-class-and-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!