Java Selenium如何从Google搜索结果中打开链接? [英] Java selenium how to open a link from google search results?

查看:46
本文介绍了Java Selenium如何从Google搜索结果中打开链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Selenium自动化测试的新手,我正在做一些基本的自动化测试,例如在Google中搜索某些内容,然后单击搜索结果中所需的链接.

I am new to automation testing in Selenium and i am doing some basic automation testing such as searching for something in Google and then clicking on a link which is required from the search results.

下面生成的代码可以工作,直到获得测试方法为止.我无法从Google搜索页面中选择链接,但在控制台上未显示任何错误.因此,我在此特定行上设置了一个线程,它提到可以找到链接名称,但是正如我在Google Check上检查的那样,该链接名称用于html代码中.

The code below, which i have produced works up until i get to the testing method. I am unable to select a link from the Google search page but i am not being shown any errors on my console. So i setup a thread on this particular line and it mentioned it could find the link name however the link name is used in the html code as i have checked on Google inspect.

我缺少明显的东西吗?我是Selenium的新手,所以能提供帮助.我也尝试从此用户响应",但是没有运气!

Am i missing something obvious? I am relatively new to Selenium so any help is appreciated. Also i have tried mirroring some code from this users response "How to click a link by text in Selenium web driver java" but no luck!

谢谢

    package com.demo.testcases;






import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;





public class MyFirstTestScript {

private static WebDriver driver;


public static void main (String[] args)  {

    SetUp();
    testing();



}

// TODO Auto-generated method stub


@setup

    public static void SetUp () {

    driver = new FirefoxDriver();
    driver.get("http://www.google.co.uk");
    System.setProperty("webdriver.gecko.driver", "usr/local/bin/geckodriver");
    driver.findElement(By.name("q")).sendKeys("BBC" + Keys.ENTER);
}   
@Test
        public static void testing()  {

    driver.findElement(By.partialLinkText("BBC - Home")).click();


}
}

推荐答案

一旦您获得了 Google主页旁边的文本 BBC 的搜索结果在包含文本 BBC-主页的链接上单击(),您可以使用以下代码块:

Once you obtain the search results for the text BBC on Google Home Page next to click() on the link containing the text BBC - Home you can use the following code block :

List <WebElement> my_list = driver.findElements(By.xpath("//div[@id='rso']//div[@class='rc']/h3[@class='r']/a"));
for (WebElement item:my_list)
{
    if(item.getAttribute("innerHTML").contains("BBC - Home"))
    item.click();
}

这篇关于Java Selenium如何从Google搜索结果中打开链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆