Home > OS >  How to find an element which has a particular sub element?
How to find an element which has a particular sub element?

Time:01-05

I want to get the text of the element with td tag. The text I want is "2021.08.13"

                         <tr>
                        <td><span>申请号:</span> <a 
 href="javascript:viewDetail(0);">CN202110930062.2</a> </td>
                        <td><span>申请日:</span> 2021.08.13 
                                                   </td>
                    </tr>

I tried the following XPath :

"td//span[.='申请日:']"

But I am getting the text value of span tag only. Can anybody tell me the correct xpath or css selector for this?

CodePudding user response:

The easiest way to get the value is to get the whole cell value and then split with specific text to get the remaining value.

celltext=driver.find_element(By.XPATH,"//td[.//span[.='申请日:']]").text
lastpart=celltext.split('申请日:')[-1]
print(lastpart)

There is another way you could grab the value using javascript executor to get the lastchildnode.

print(driver.execute_script('return arguments[0].lastChild.textContent;', driver.find_element(By.XPATH,"//td[.//span[.='申请日:']]")))

CodePudding user response:

If that string you need is the last text(), you could use:

  1. the following-sibling axis like this :

    //td/span[.='申请日:']/following-sibling::text()

  2. the last() text() like this

    //td[span[.='申请日:']]/text()[last()]

  •  Tags:  
  • Related