how to find xpath of an element skipping the inner

2020-04-12 08:08发布

问题:

I have a complex html structure with lot of tables and divs.. and also the structure might change. How to find xpath by skipping the elements in between. for example :

<table>
  <tr>
    <td>
      <span>First Name</span>
    </td>
    <td>
      <div>
        <table>
          <tbody>
            <tr>
              <td>
                <div>
                  <table>
                    <tbody>
                      <tr>
                        <td>
                          <img src="1401-2ATd8" alt="" align="middle">
                        </td>
                        <td><span><input atabindex="2"  id=
                        "MainLimitLimit" type="text"></span></td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </td>
  </tr>
</table>

I have to get the input element with respect to the "First Name" span

eg :

By.xpath("//span[contains(text(), 'First Name')]/../../td[2]/div/table/tbody/tr/td/table/tbody/tr/td[2]/input")

but.. can I skip the between htmls and directly access the input element.. something like?

By.xpath("//span[contains(text(), 'First Name')]/../../td[2]//input[contains@id,'MainLimitLimit')]")

回答1:

You can try this Xpath :

//td[contains(span,'First Name')]/following-sibling::td[1]//input[contains(@id, 'MainLimitLimit')]

Explanation :

select <td><span>First Name</span></td> element :

//td[contains(span,'First Name')]

then get <td> element next to above <td> element :

/following-sibling::td[1]

then get <input> element within <td> element selected in the 2nd step above :

//input[contains(@id, 'MainLimitLimit')]


回答2:

You can use // which means at any level

By.xpath("//span[contains(text(), 'First Name')]//td[2]/input[contains@id,'MainLimitLimit')]")


回答3:

you can use the "First Name" span as a predicate. Try the code below

//td[preceding-sibling::td[span[contains(text(), 'First Name')]]]//input[contains(@id,'MainLimitLimit')]