硒。按类查找元素并使用JS从DOM中删除它

时间:2017-11-23 05:48:16

标签: javascript c# selenium dom

对我有用的代码。我先获取消息数量然后将其删除。

    public static void RemoveMSGs()
    {
        // Remove messages from DOM using JS
        int MessagesOnThePage = Program.ChromeDriver.FindElementsByClassName("GLS-JUXDKAD").Count;
        Console.WriteLine("Total messages: " + MessagesOnThePage);

        while (MessagesOnThePage != 0)
        {
            MessagesOnThePage--;
            {
                try
                {
                    Program.js.ExecuteScript("var ele = document.querySelector('.GLS-JUXDKAD'); ele.parentNode.removeChild(ele); "); // This code removes the whole message
                    Console.WriteLine("JS execution command: remove message on the page. Total messages on the page: " + MessagesOnThePage);
                }
                catch
                {
                    Console.WriteLine("JS error. Can't remove message on the page. There is no more messages. Total messages: " + MessagesOnThePage);
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

只需在您的selenium代码中包含以下行

即可
var ele = document.querySelector('GLS-JUXDFAD');
ele.parentNode.removeChild( ele );