我正在做一个项目,我必须将Google搜索结果与其他搜索结果引擎进行比较。我打算通过使用Selenium工具比较搜索结果来执行此测试。
我想做的是:
现在我从stackoverflow网站获得了如下代码。根据我的要求修改。它正在获取第一个结果的标题和链接。我如何获得整个页面的标题和链接?
我的代码是:
package gooPkg;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class testSearch {
public static void main(String[] args) {
String baseUrl = "https://www.google.co.in/";
WebDriver driver = new FirefoxDriver();
//String underConsTitle = "Under Construction: Mercury Tours";
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(baseUrl);
// Enter the query string "Cheese"
WebElement query = driver.findElement(By.name("q"));
query.sendKeys("obama twitter");
query.submit();
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
WebElement resultsDiv = driver.findElement(By.className("gssb_e"));
if (resultsDiv.isDisplayed()) {
break;
}
}
List<WebElement> weblinks = driver.findElements(By.xpath("/html/body/div/div[3]/div[2]/div[6]/div/div[4]/div/div[2]/div[2]/div/ol/li/div/div/h3/a"));
for (WebElement suggestion : weblinks) {
System.out.println(suggestion.getText()+"\n");
System.out.println("==> "+suggestion.getAttribute("href")+"\n");
}
}}
答案 0 :(得分:1)
您可以使用findElements获取所有搜索结果标题&amp;链接。
String baseUrl = "https://www.google.co.in/";
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(baseUrl);
WebElement query = driver.findElement(By.name("q"));
query.sendKeys("obama twitter");
query.submit();
//==============Here logic goes =======================
//get all the search result
List<WebElement> allSearchResults=driver.findElements(By.cssSelector("ol li h3>a"));
//iterate the above list to get all the search titles & links from that page
for(WebElement eachResult : allSearchResults) {
System.out.println("Title : "+eachResult.getText()+", Link : "+eachResult.getAttribute("href"));
}
EDIT-I
尝试使用以下逻辑。在网址中包含搜索字词。
String baseUrl = "https://www.google.co.in/#q=webdriver";
driver.get(baseUrl);
//get all the search result
List<WebElement> allSearchResults=driver.findElements(By.cssSelector("ol li h3>a"));
//iterate the above list to get all the search titles & links from that page
for(WebElement eachResult : allSearchResults) {
System.out.println("Title : "+eachResult.getText()+", Link : "+eachResult.getAttribute("href"));
}