简体   繁体   中英

Cant find and click button By.XPath(“//button[@title='MyCompany']”).Click()

Trying to find an click the element of a button "MyCompany". However I get NoSuchElementExist when calling driver.FindElement(By.XPath("//button[@title='MyCompany']").Click() ? What am I doing wrong?

在此处输入图像描述

There are 2 things you can try:

First, use the full xpath (in chrome dev tools, right click element, copy > full Xpath).

Second, because it is angular, sometimes the element likes being in the viewport or the page needs to be loaded all the way first. This can be accomplished by using 'IJavaScriptExecutor'.

//use full xpath here instead
var xPathButton = @"//button[@title='MyCompany']";
    using (var driver = new ChromeDriver())
        {

            driver.Navigate().GoToUrl("https://website.com);
            //scrolls to bottom to ensure page load
            
           ((IJavaScriptExecutor)driver).ExecuteScript("window.scrollTo(0, document.body.scrollHeight - 1)"); 
            Task.Delay(2000).Wait();
            
            var companyButton = driver.FindElementByXPath(xPathButton);
            ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click();", companyButton);
         }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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