简体   繁体   English

C#WebBrowser可以自动点击div按钮吗?

[英]C# WebBrowser is it possible to automaticly click an div button?

I am testing around with WebBrowser in C# and I found a site which has got an button but the button has no ID it's a div. 我正在使用C#中的WebBrowser进行测试,我发现一个网站有一个按钮但按钮没有ID它是一个div。

<div class="pc-image-info-box-button-btn-text pc-cursor"><i class="fa fa-heart" aria-hidden="true"></i>GO</div>

Is it possible to tell the WebBrowser to click this button? 是否可以告诉WebBrowser单击此按钮? When the form starts the WebBrowser naviagates to the site than the programm wait's for the WebBrowser to finish loading and once its loaded it should click on the button. 当表单启动时,WebBrowser导航到站点而不是编程等待WebBrowser完成加载,一旦加载它就应该单击按钮。

Thats my try right now: 多数民众赞成在我的尝试:

            webBrowser1.Url = new Uri(textBox2.Text);

        while(webBrowser1.ReadyState != WebBrowserReadyState.Complete)
        {
            Application.DoEvents();
        }

        webBrowser1.Navigate("javascript: document.getElementsByClassName('pc-image-info-box-button-btn-text pc-cursor')[0].click();void(0);");

But it doesn't work. 但它不起作用。

Of course it works, but only if your div has an onclick event handler set. 当然它可以工作,但前提是你的div有一个onclick事件处理程序集。

var div = document.createElement('div')
// undefined
div.onclick = function(){ console.log(':)')}
// ƒ (){ console.log(':)')}
div.click()
// :)

Look at this example: 看看这个例子:

<html>
    <head>
    </head>
<body>
    <h2 class="text-center">example</h2>
    <div class="pc-image-info-box-button-btn-text pc-cursor" ><i class="fa fa-heart" aria-hidden="true"></i>GO</div>


</body>
    <script type="text/javascript">
        // attach function on document loaded event
        document.addEventListener('DOMContentLoaded', function(){ 

            // Your selector will be different most likely
            var element = document.getElementsByClassName('pc-image-info-box-button-btn-text')[0];

            // add click event listener to selected element
            element.addEventListener("click", clickFunc);

            // declare function which fires on click
            function clickFunc(){ alert('clicked!'); }

            // trigger  element click event
            element.dispatchEvent(new Event('click'));
        }, false);
    </script>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM