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