一尘不染

Selenium Webdriver单击Google搜索

selenium

我正在搜索文字“奶酪!”
在Google主页上,并不确定在按搜索按钮后如何才能单击搜索到的链接。例如,我想单击搜索页面顶部的第三个链接,然后如何找到标识的链接并单击它。到目前为止,我的代码:

package mypackage;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.chrome.ChromeDriver; 
import org.openqa.selenium.support.ui.WebDriverWait;

public class myclass {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "C:\\selenium-java-2.35.0\\chromedriver_win32_2.2\\chromedriver.exe");

         WebDriver driver = new ChromeDriver(); 
         driver.get("http://www.google.com"); 
         WebElement element = driver.findElement(By.name("q"));
         element.sendKeys("Cheese!");
         element.submit();

         //driver.close();
    }



}

阅读 315

收藏
2020-06-26

共1个答案

一尘不染

Google缩小了CSS类等,因此识别所有内容并不容易。

另外,您还有一个问题,必须“等待”,直到站点显示结果为止。我会这样做:

public static void main(String[] args) {

    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.google.com");
    WebElement element = driver.findElement(By.name("q"));
    element.sendKeys("Cheese!\n"); // send also a "\n"
    element.submit();

    // wait until the google page shows the result
    WebElement myDynamicElement = (new WebDriverWait(driver, 10))
              .until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));

    List<WebElement> findElements = driver.findElements(By.xpath("//*[@id='rso']//h3/a"));

    // this are all the links you like to visit
    for (WebElement webElement : findElements)
    {
        System.out.println(webElement.getAttribute("href"));
    }
}

这将为您打印:

2020-06-26