简体   繁体   English

Selenium 抛出 Element not found 异常

[英]Selenium throws Element not found exceptions

I am new to selenium with java and trying to automate some scenarios.我是使用 java 进行 selenium 的新手,并试图自动化一些场景。 I wrote a code to insert text in the field but the issue is that the element displays when I search for the element in the dom by xpath, id or name but when I run my script.我编写了一个代码来在字段中插入文本,但问题是当我通过 xpath、id 或 name 在 dom 中搜索元素但运行我的脚本时,元素会显示。

I get a "no such element found" error.我收到“找不到这样的元素”错误。 Below is my code and below is the XML.下面是我的代码,下面是 XML。

My code:我的代码:

public void SearchByZipCode(String Zipcode) {
        WebElement addressfield = driver.findElement(By.name("addressline"));
        addressfield.sendKeys(Zipcode);
        WebElement search = driver.findElement(By.id("locator_submit"));
        search.click();
        WebElement result = driver.findElement(By.xpath("//div[@id='panel']//span[2]"));
        String text = result.getText();

        if (text.contains(Zipcode)) {
            System.out.println("Passed! Expected results for: " + Zipcode + "Actual result displayed for: " + text);
        } else {
            System.out.println("Failed! Expected results for: " + Zipcode + "Actual result displayed for: " + text);
        }

HTML: HTML:

    <input tabindex="3" style="padding:8px; width:90%; border:1px solid 
    #cdcdcd;" class="addressentry" type="text" size="40" name="addressline" 
    id="inputaddress" value="Enter street address, city, state or ZIP" 
    onclick="clear_inputbox(this);">

I would recommend first use method, which will wait for this element to appear and become active.我会推荐 first use 方法,它将等待此元素出现并变为活动状态。 Then enter your value.然后输入您的值。 Also, better to use ID as selector, since it is available in your page.此外,最好使用 ID 作为选择器,因为它在您的页面中可用。

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

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