Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python selenium, how can i delete an element?

I've been trying the last hour to delete an element by without any success. And the element can only be reached via class name. I've tried:

js = "var aa=document.getElementsByClassName('classname')[0];aa.parentNode.removeChild(aa)"
driver.execute_script(js)

I get error that parentNode is undefined.

So what the best way to delete an element using Selenium?

like image 799
Captain_Meow_Meow Avatar asked Mar 19 '14 18:03

Captain_Meow_Meow


People also ask

How do you delete an element in Selenium?

We can delete an element in Selenium webdriver using Python with the help of JavaScript Executor. Selenium is not capable of modifying the structure of DOM directly. It has the feature of injecting JavaScript into the webpage and changing the DOM with the help execute_script method.

How do you delete an element?

The remove() method removes an element (or node) from the document.


Video Answer


3 Answers

I do not know of a Selenium method that is designed specifically to remove elements. However, you can do it with:

element = driver.find_element_by_class_name('classname')
driver.execute_script("""
var element = arguments[0];
element.parentNode.removeChild(element);
""", element)

find_element_by_class_name will raise an exception if the element does not exist. So you don't have to test whether element is set to a sensible value. If the method returns, then it is set. Then you pass the element back to execute_script. The arguments passed to execute_script in Python appear in JavaScript as the arguments object. (It's the same as the arguments object that you normally get with any JavaScript function. Behind the scenes Selenium wraps the JavaScript code in an anonymous function.)

Or you can use a solution that relies on JavaScript to find the element:

driver.execute_script("""
var element = document.querySelector(".classname");
if (element)
    element.parentNode.removeChild(element);
""")

This solution is much better if you happen to be using a remote server to run your test (like Sauce Labs, or BrowserStack). There's a non-negligible cost to communications between the Selenium client and the server.

like image 70
Louis Avatar answered Oct 22 '22 09:10

Louis


getElementByClassName is not a method on document. You'll want to use

getElementsByClassName('classname')[0]...

but only if you're sure it's the only one with that class.

like image 26
jstaab Avatar answered Oct 22 '22 09:10

jstaab


Thanks for the input Louis. I built the following python function that uses the JavaScript you suggested:

def excludeTagFromWebDriver(driver : WebDriver, selector : str):
    i = 0
    soup = BeautifulSoup(driver.page_source, 'html.parser') # Parsing content using beautifulsoup
    while soup.find(selector):
        # print(soup.find(selector))
        js = """
            var element = document.querySelector(""" + "'" + selector + "'" + """);
            if (element)
                element.parentNode.removeChild(element);
            """
        driver.execute_script(js)
        soup = BeautifulSoup(driver.page_source, 'html.parser') # Parsing content using beautifulsoup
        i += 1
        # print('Removed tag with selector ' + "'" + selector + "'" + ' with nr: ', i)
    print('Removed ' + str(i) + ' tags with the selector ' + "'" + selector + "'" + " and all it's children tags.")
    return driver

driver = excludeTagFromWebDriver(driver,"sup")
like image 3
Christian Avatar answered Oct 22 '22 09:10

Christian