简体   繁体   中英

Get href from link above another element with Selenium

I'm using selenium and I need to get an href from a link that is above many tags!

But the only information that I can use and I have for sure, is the text "Test text!" from the h3 tag: Here is the example:

<a href="/link/post" class="link" >
    <div class="inner">
      <div class="header flex">
        <h3 class="mb-0">
          Test text!
          </h3>
       </div>
     </div>
</a>

Try using the following xpath to locate the desired element:

//a[@href and .//h3[contains(text(),'Test text!')]]

So, to get the href value you have to

from selenium.webdriver.common.by import By
href = driver.find_element(By.XPATH, '//a[@href and .//h3[contains(text(),'Test text!')]]')

An alternative to the approach in Prophet's answer would be to use a XPATH like

//h3[contains(text(),"Test text!")]]//ancestor::a

ie first search for the h3 tag and then for an a tag above.

Prophet's answer uses the opposite approach, first find all a tags and then only keep the one with the correct h3 tag below.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM