简体   繁体   中英

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?

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.

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.

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")

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