javascript Python selenium,如何删除元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22515012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:17:23  来源:igfitidea点击:

Python selenium, how can i delete an element?

javascriptpythonselenium

提问by Captain_Meow_Meow

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.

我收到未定义 parentNode 的错误。

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

那么使用 Selenium 删除元素的最佳方法是什么?

采纳答案by jstaab

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

getElementByClassName 不是 上的方法document。你会想要使用

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

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

但前提是您确定它是该课程中唯一的一个。

回答by Louis

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

我不知道专门为删除元素而设计的 Selenium 方法。但是,您可以这样做:

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

find_element_by_class_namewill raise an exception if the element does not exist. So you don't have to test whether elementis 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_scriptin Python appear in JavaScript as the argumentsobject. (It's the same as the argumentsobject that you normally get with any JavaScript function. Behind the scenes Selenium wraps the JavaScript code in an anonymous function.)

find_element_by_class_name如果元素不存在,将引发异常。所以你不必测试是否element设置为一个合理的值。如果该方法返回,则设置它。然后将元素传递回execute_script. execute_script在 Python 中传递给的参数在 JavaScript 中作为arguments对象出现。(它与arguments您通常使用任何 JavaScript 函数获得的对象相同。Selenium 在幕后将 JavaScript 代码包装在一个匿名函数中。)

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

或者您可以使用依赖于 JavaScript 的解决方案来查找元素:

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

This solution is much betterif 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.

如果您碰巧使用远程服务器来运行测试(如 Sauce Labs 或 BrowserStack),则此解决方案会更好。Selenium 客户端和服务器之间的通信成本不可忽略。