Home > other >  Remove parents of the elements in Python Selenium
Remove parents of the elements in Python Selenium

Time:05-11

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 > parent only.

So for example:

<div >
  <div >
    <div >
      <div >
         <span > 5% </span>
      </div>
    </div>
  </div>
</div>

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

    <div >
      <div >
         <span > 5% </span>
      </div>
    </div>

So what should left is:

<div >
  <div >

  </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 >
  <div >
    <div >
      <div >
         <span > 5% </span>
      </div>
    </div>
  </div>
</div>


<div >
  <div >
    <div >
      <div >
         <span > 95% </span>
      </div>
    </div>
  </div>
</div>


<div >
  <div >
    <div >
      <div >
         <span > 32% </span>
      </div>
    </div>
  </div>
</div>


<div >
  <div >
    <div >
      <div >
         <span > 15% </span>
      </div>
    </div>
  </div>
</div>

CodePudding user response:

get to the parent of the parent:

 driver.execute_script("arguments[0].parentElement.parentElement.remove();", item)
  • Related