Skip to content
Advertisement

How do I delete/exclude selected children nodes from the parent node in Selenium/Python?

Say, I’d like to get the article without to_del (could contain 0 or several elements). Seems driver.execute_script is the solution. But how to code it?

article = driver.find_element_by_xpath("//section[contains(@class, 'am-article')] //div[@class='article-layout']")

to_del = article.find_elements_by_xpath("./div[contains(@class, 'am-article__image') or @class='facebook-paragraph' or @class='am-article__source']")

enter image description here

to_del = article.find_elements_by_xpath(".//*[ contains(@class, 'am-article__heading' ) or contains(@class, 'am-article__image') or contains(@class, 'facebook-paragraph') or contains(@class, 'twitter-tweet') or contains(@class, 'am-article__source') or contains(@class, 'article-tags') or contains(text(), 'zytaj także:')]")

Advertisement

Answer

https://www.w3schools.com/jsref/met_element_remove.asp

The remove() method removes the specified element from the DOM.

to_del = article.find_elements_by_xpath("./div[contains(@class, 'am-article__image') or @class='facebook-paragraph' or @class='am-article__source']")
while  len(to_del):
     driver.execute_script("arguments[0].remove()",to_del [0])
     article = driver.find_element_by_xpath("//section[contains(@class, 'am-article')] //div[@class='article-layout']")
     to_del = article.find_elements_by_xpath("./div[contains(@class, 'am-article__image') or @class='facebook-paragraph' or @class='am-article__source']")

we are using while and refinding the elements to avoid stale element error as the DOM changes whe nyou delete a node

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement