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

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

问题描述

我是 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 搜索页面选择链接,但我的控制台上没有显示任何错误.所以我在这个特定的行上设置了一个线程,它提到它可以找到链接名称,但是在 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 比较陌生,因此感谢您的任何帮助.我也尝试从这个用户响应中镜像一些代码"如何在 Selenium 网络驱动程序 java 中通过文本点击链接"但没有运气!

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 Home Page 上获得文本 BBC 的搜索结果click() 在包含文本 BBC - Home 的链接上,您可以使用以下代码块:

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 如何从谷歌搜索结果中打开链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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