17

「チーズ!」というテキストを検索しています。検索ボタンを押した後、検索されたリンクをクリックする方法がわかりません。たとえば、検索ページで上から 3 番目のリンクをクリックしたいのですが、どうすればそのリンクを特定してクリックできますか。これまでの私のコード:

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();
    }



}
4

7 に答える 7

4
@Test
public void google_Search()
{
    WebDriver driver;
    driver = new FirefoxDriver();
    driver.get("http://www.google.com");
    driver.manage().window().maximize();

    WebElement element = driver.findElement(By.name("q"));
    element.sendKeys("Cheese!\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"));

    //Get the url of third link and navigate to it
    String third_link = findElements.get(2).getAttribute("href");
    driver.navigate().to(third_link);
}
于 2017-02-04T18:31:31.843 に答える
1

Google Web の簡単な調査に基づいて、これはページ リスト内のリンクへの CSS パスになります。

ol[id="rso"] h3[class="r"] a

だからあなたは次のようなことをするべきです

String path = "ol[id='rso'] h3[class='r'] a";
driver.findElements(By.cssSelector(path)).get(2).click();

ただし、ベスト プラクティスとして実際には推奨されていないものや JQuery ロケーターを使用することもできますが、 Arquillianxpath Graphene 以外の場所で使用できるかどうかはわかりません

于 2013-08-22T18:05:47.927 に答える
0
public class GoogleSearch {

    public static void main(String[] args) {

        WebDriver driver=new FirefoxDriver();
        driver.get("http://www.google.com");
        driver.findElement(By.xpath("//input[@type='text']")).sendKeys("Cheese");   
        driver.findElement(By.xpath("//button[@name='btnG']")).click();
        driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); 
        driver.findElement(By.xpath("(//h3[@class='r']/a)[3]")).click();
        driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); 
    }
}
于 2014-08-04T18:07:52.867 に答える
0

Google 検索ボックスを見つけるための単純な Xpath は次のとおりです。Xpath=//span[text()='Google 検索']

于 2014-08-04T16:51:06.167 に答える