![](/img/trans.png)
[英]Selenium C# - how can i implement click on button without button name and id
[英]C# Selenium how can I implement click on button without id
C# Selenium 如何實現沒有 id 的點擊按鈕
這是html:
<div class="fe-margin">
<button class="btn btn-default" data-bind="click: $root.addParameter, enable: $root.selectedParameter() == null" type="button"/>
Add parameter button
</div>
是的,你可以。 使用 xpath 的類名,您可以執行單擊操作。
例如:
driver.FindElement(By.ClassName("AddContentBTN")).Click();
Selenium
提供了各種搜索選項來查找元素。 查看documentation
以獲取更多詳細信息。
這些是廣泛使用的搜索選項。
用法:
var element = driver.FindElement(By.ClassName("btn-default")); // works for your case.
var element = driver.FindElement(By.Id("closeButton"));
var element = driver.FindElement(By.XPath("//*[@class='menu_bg']/ul/li[3]"));
var element = driver.FindElement(By.CssSelector("#import>a"));
使用任何選擇器獲取元素后,您只需要Click
它即可。
element.Click();
試試這個 Xpath -
var element = driver.FindElement(By.XPath("//button[@class ='btn btn-default']"));
element.Click();
謝謝
您可以單擊使用 JavaScript 不可見的按鈕
IJavaScriptExecutor executor = driver as IJavaScriptExecutor;
executor.ExecuteScript("arguments[0].click();", ElementToClick)
您可以通過ClassName
使用其中一個類來完成
driver.FindElement(By.ClassName("btn-default")).Click();
// or
driver.FindElement(By.ClassName("btn")).Click();
或者通過帶有兩個類的CssSelector
driver.FindElement(By.CssSelector(".btn.btn-default")).Click();
編輯
錯誤
元素在該點不可點擊
意味着 Selenium 看不到按鈕,所以它不能點擊它。 你需要先滾動到它
IWebElement button = driver.FindElement(By.ClassName("btn-default")); // locate the button, can be done with any other selector
Actions action = new Actions(driver);
action.MoveToElement(button).Perform(); // move to the button
button.Click();
使用此 XPath 按文本查找按鈕:
"//div[normalize-space(.)='Add parameter button']/button"
此處提供的答案提供了您完成這項工作的大部分方法。 這是由 Selenium 提供的選擇類並“手動”使用 JavaScript。 偶爾我會遇到奇怪的按鈕和菜單實現,這些方法都不適合我。 然后我所做的是將鼠標移到按鈕上並進行自由點擊。 Selenium 提供了一種方法:
Actions action = new Actions(Driver);
action.MoveToElement(/IWebElement here/).Perform();
action.Click();
or
action.SendKeys(OpenQA.Selenium.Keys.Enter).Perform();
如果這也失敗了,我的最后一張牌將是圖像識別庫,就像 github 上的一些 c# 包裝的 Sikuli 包一樣。
IWebElement btn = Firefox.FindElement(By.ClassName("btn")); btn.Click();
這應該做。 我發現使用 ClassName 的一部分可以完成這項工作。
您可以使用按鈕名稱或文本:
driver.FindElements(by.TagName("button")).FirstOrDefault(ele=>ele.GetAttribute("Name").Equals("Submit")).click();
或者,區分大小寫:
driver.FindElements(by.TagName("button")).FirstOrDefault(ele=>ele.GetAttribute("Name").ToLower().Equals("Submit")).click();
或者,就您而言:
driver.FindElements(by.TagName("button")).FirstOrDefault(ele=>ele.Text.Equals("Name").Click();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.