如何执行网页上的点击按钮?

问题描述

当网页上显示按钮时,我想以编程方式单击该按钮,有办法吗?

这是按钮,没有ID,只有ID;

<div class="VotingButtons"><button class="VotingButton VotingButton--upvote btn-white" type="button">Like</button>

有关此按钮的更多信息:

<div class="VotingWrapper VotingWrapper--isBlocking"><p class="VotingWrapper__text"><strong>Do you like this image?</strong></p><div class="VotingButtons"><button class="VotingButton VotingButton--upvote btn-white" type="button">Like</button><button class="VotingButton VotingButton--downvote btn-white" type="button"><span class="VotingButton__text--hideOnMobile">Dislike</span></button></div></div>

我尝试使用此代码,但是它不起作用:

private async void Btn_GoToDirectly_Click(object sender,EventArgs e)
    {
        
        var script = @"
document.getElementsByClassName('VotingButton VotingButton--upvote btn-white')[0].click();
browser.ExecuteScriptAsync(script);
    ";
            browser.ExecuteScriptAsync("document.getElementByClassName('VotingButton VotingButton--upvote btn-white').click()");

解决方法

变量脚本具有的字符串具有getElementsByClassName,并使用索引0处的结果(似乎正确), 但是您实际运行的脚本具有getElementByClassName,单数不存在(当然也没有索引器)..您是否尝试运行脚本变量?

    string script = @"document.getElementsByClassName('VotingButton VotingButton--upvote btn-white')[0].click();"
    browser.ExecuteScriptAsync(script);

除了cefsharp代码外,此操作无所不能-但是,如果您在javascript中有类似的内容,则script中的代码应可通过cefsharp工作。

let like= function(){
    console.log("like");
};

let trigger= function(){
console.log("trigger");
document.getElementsByClassName('VotingButton VotingButton--upvote btn-white')[0].click();
};
<html>
<body>
<div class="VotingWrapper VotingWrapper--isBlocking">
<p class="VotingWrapper__text">
<strong>Do you like this image?</strong>
</p>
<div class="VotingButtons">
<button onclick="like()" class="VotingButton VotingButton--upvote btn-white" type="button">Like</button>
<button class="VotingButton VotingButton--downvote btn-white" type="button">
<span class="VotingButton__text--hideOnMobile">Dislike</span>
</button>
</div>
</div>
<button onclick="trigger()" type="button">Trigger</button>
</body>
</html>

,

您可以使用硒,

Nuget导入Selenium.RC,Selenium.Support,Selenium.WebDriver,

 using (IWebDriver driver = new OpenQA.Selenium.IE.InternetExplorerDriver())
     {
         driver.Navigate().GoToUrl("http://www.xxurl.com");  
         driver.FindElements(By.ClassName("VotingButton VotingButton--upvote btn-white")).Click();
     }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...