【问题标题】:How can I write a selenium java code to click on the search result? [duplicate]如何编写 selenium java 代码来点击搜索结果? [复制]
【发布时间】:2020-06-22 09:14:30
【问题描述】:
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.setProperty("webdriver.gecko.driver", "F:\\3rd year\\IS 3103\\New folder (2)\\geckodriver.exe");
        WebDriver objDriver= new FirefoxDriver();
        objDriver.get("http://www.google.com");
        objDriver.findElement(By.xpath("/html/body/div/div[3]/form/div[2]/div[1]/div[1]/div/div[2]/input")).sendKeys("GMAIL", Keys.ENTER);
        objDriver.findElement(By.xpath("/html/body/div[6]/div[2]/div[9]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div[1]/a/h3")).click();;

    }

}

这是我写的代码。我想编写一个 selenium java 代码来在 google 中搜索 GMAIL 并通过单击它转到相应的结果。得到搜索结果后不执行,出现如下错误。

线程“主”org.openqa.selenium.NoSuchElementException 中的异常:无法定位元素:/html/body/div[6]/div[2]/div[9]/div[1]/div[2 ]/div/div[2]/div[2]/div/div/div[1]/div/div[1]/a/h3

【问题讨论】:

    标签: java selenium selenium-webdriver automated-tests


    【解决方案1】:

    您不能对 google 页面进行硬编码,因为 google 元素每天都在更新

    以下代码打开google,输入“testing”并存储所有结果。最后点击“testing types

    public class GooglesearchTests {
    
    public static void main(String[] args) throws Exception {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\User\\Downloads\\chromedriver83\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.google.com/");
        driver.findElement(By.name("q")).sendKeys("Testing");
        Thread.sleep(Long.parseLong("1000"));
        List<WebElement> LIST = driver.findElements(By.xpath("//ul[@role='listbox']//li/descendant::div[@class='sbl1']"));
        System.out.println(LIST.size());
    
    
        for (int i = 0; i < LIST.size(); i++)
        {
            //System.out.println(LIST.get(i).getText());
            if (LIST.get(i).getText().contains("testing types"))
            {
                LIST.get(i).click();
                break;
            }
        }
    }
    

    }

    【讨论】:

    • 如何点击搜索结果?
    • 上面的代码是我输入为“测试”,然后从显示的结果中选择“测试类型”。
    • for (int i = 0; i
    • 定位元素时请使用相对xpath
    • youtube.com/watch?v=6RaDZhfXHI8&t=766s此链接将帮助您解决此问题
    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 2019-03-13
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    相关资源
    最近更新 更多