首页 > 解决方案 > 如何使用 Selenium 和 Java 在谷歌搜索结果页面上单击带有文本的元素作为谷歌的 Gmail

问题描述

我正在编写我的第一个 selenium java 脚本,如下所示。

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class testClass {
    WebDriver driver;
    

    public void launchBrowser() throws InterruptedException {   
        System.setProperty("webdriver.chrome.driver",
        "C:\\Users\\acer\\Downloads\\selenium\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.google.com/");
        Thread.sleep(1000);
        
    }
    
    private void sendData() throws InterruptedException {
        WebElement we1 = driver.findElement(By.name("q"));
        we1.sendKeys("GMAIL");
        we1.sendKeys(Keys.ENTER);
        Thread.sleep(2000); 
        we1.findElement(By.xpath("//a[text()='Gmail by Google']")).click();
        Thread.sleep(2000); 

    }


    public static void main(String[] args) throws InterruptedException {
        testClass obj=new testClass();
        obj.launchBrowser();
        obj.sendData();
        

    }

}

它没有错误。但

we1.findElement(By.xpath("//a[text()='Gmail by Google']")).click();

不管用。它不会点击Google 的 Gmail。有没有其他方法可以做到这一点?

标签: javaseleniumselenium-webdriverxpathwebdriver

解决方案


文本Gmail by Google<h3>位于祖先标记的子标记内<a>

GmailByGoogle

所以而不是:

we1.findElement(By.xpath("//a[text()='Gmail by Google']")).click();

你需要使用:

we1.findElement(By.xpath("//h3[text()='Gmail by Google']")).click();

推荐阅读