org.openqa.selenium.NoSuchElementException:无法找到元素:-搜索字段

时间:2018-11-19 07:06:58

标签: java selenium-webdriver

我正在尝试在linkedin(https://www.linkedin.com/learning/me?trk=nav_neptune_learning)的学习搜索字段中进行搜索

  1. 登录到linkedin
  2. 点击“学习”链接(右上角)
  3. 我正在发送Tab键并到达“搜索”字段
  4. 最后使用xpath找到“搜索”字段,并且我正在发送搜索关键字(.sendKeys(“ Python”)

硒与Java:

driver.findElement(By.xpath("//div[@class='search-container']/descendant::input[@type='text']")).sendKeys("Python");

到步骤3为止,它都起作用,突出显示搜索字段。

最后一步总是失败,只有以下例外

org.openqa.selenium.NoSuchElementException:无法找到元素:

我尝试了以下xpath:

//div[@class='container global-nav__container']//div[@class='search-container']/artdeco-typeahead[@id='ember863']/div/input[@type='text']
//div[@class='search-container']/descendant::input[@type='text']
//div[@class='search-container']/artdeco-typeahead[@id='ember863']/div/input[@type='text']
//div[@class='search-container']/artdeco-typeahead/div/input[@type='text']

enter image description here 上面所有的xpath都有意思,我可以在浏览器中找到该元素,但是相同的xapth在硒代码中不起作用。

我的代码-步骤4

@Test
    public static void search() throws InterruptedException, AWTException
    {

        Robot robot = new Robot();
        for ( int i=0; i<=5;i++)
        {
        robot.keyPress(KeyEvent.VK_TAB);
        Thread.sleep(2000);
        }
        driver.findElement(By.xpath("//input[@type='text']")).sendKeys("Python");
    }

2 个答案:

答案 0 :(得分:1)

NoSuchElementException通常在两种情况下发生。

  1. Webelement定位器错误。 (看来情况并非如此)
  2. 您甚至还在尝试将Webelement加载到页面上之前找到它。(这似乎是您的问题)

之所以收到“ NoSuchElementException”,是因为甚至在页面上的Webelement完全加载之前就已经输入了文本。

我建议您等到要查找的Web元素首先被加载,然后再使用sendkeys。使用可以使用WebDriverWait

所以重构后的代码应该看起来像这样。

//Initializing the 'wait' with a 30 seconds deplay before it throws a NoSuchElementException
WebDriverWait wait = new WebDriverWait(driver,30);

wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("input[placeholder='Search for skills, subjects or software']"));

driver.findElement(By.cssSelector("input[placeholder='Search for skills, subjects or software']")).sendKeys("Python");

答案 1 :(得分:0)

以下代码将为您工作:

driver.findElement(By.cssSelector("input[placeholder='Search for skills, subjects or software']")).sendKeys("Python");
相关问题