Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove parents of the elements in Python Selenium

The HTML is located below, If the span value is less than 20%, then I want to remove the span child up until the <div class="action"> parent only.

So for example:

<div class="item">
  <div class="info">
    <div class="action">
      <div class="content">
         <span class="content-name"> 5% </span>
      </div>
    </div>
  </div>
</div>

From the above HTML, these code should only be removed:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    <div class="action">
      <div class="content">
         <span class="content-name"> 5% </span>
      </div>
    </div>

So what should left is:

<div class="item">
  <div class="info">

  </div>
</div>

This is my current python code:

items = WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//span[@class='content-name']")))
for item in items:
    percentage_text = re.findall("\d+", item.text)[0]
    if int(percentage_text) <= 20:
        driver.execute_script("arguments[0].remove();", item)

But it only removes the span class and not its parent.

Here is the full HTML, I think it needs javascript to remove elements but I am very new on javascript I researched for more than 2 hours and I still can’t find solutions. Thank you very much.

<div class="item">
  <div class="info">
    <div class="action">
      <div class="content">
         <span class="content-name"> 5% </span>
      </div>
    </div>
  </div>
</div>


<div class="item">
  <div class="info">
    <div class="action">
      <div class="content">
         <span class="content-name"> 95% </span>
      </div>
    </div>
  </div>
</div>


<div class="item">
  <div class="info">
    <div class="action">
      <div class="content">
         <span class="content-name"> 32% </span>
      </div>
    </div>
  </div>
</div>


<div class="item">
  <div class="info">
    <div class="action">
      <div class="content">
         <span class="content-name"> 15% </span>
      </div>
    </div>
  </div>
</div>

>Solution :

get to the parent of the parent:

 driver.execute_script("arguments[0].parentElement.parentElement.remove();", item)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading