問題描述
如何使用硒驗證谷歌搜索結果是否包含特定文本? (How to verify whether google search results consist of a specific text using selenium?)
我想驗證 google 搜索結果是否包含特定文本。以下是我的代碼:
public static void main(String[] args) {
System.out.println("setting the driver path");
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Arushi\\Desktop\\Arushi\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://google.com");
driver.manage().window().maximize();
WebElement textbox = driver.findElement(By.name("q"));
textbox.sendKeys("stack");
WebElement button = driver.findElement(By.name("btnG"));
button.click();
String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains("stackoverflow.com"));
但是上面的代碼沒有給出正確的結果。getText() 方法獲取頁面“google.com”的正文文本,而不是執行搜索後加載的頁面。
我想知道2件事:1.為什麼上面的getText()是從google.com提取正文2.在google搜索結果中搜索特定文本的正確方法是什麼.
注意:我也嘗試過 driver.getPageSource().contains() 方法,但即使這樣也沒有給出正確的結果。
參考解法
方法 1:
I would attack this by identifying the exact elements that represent search results on the DOM, then loop over each instance of a search result to validate the text for my search term. Simply searching the full page for some text opens up some opportunities for inaccurate results.
By looking at the DOM of a google search result page, we can see that each of the search results live in a node with class .rc
. Children of that node, with classes .r
and .s
represent the result name and description, respectively.
I'll assume for this example that you'd like to check the search result names for your search term, but you should be able to easily refactor the code below to your specific needs.
public static void main(String[] args) {
// First, let's declare our search term
private String searchTerm = "Selenium";
// Then, let's start our WebDriver and navigate to google
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
driver.manage().window().maximize();
// Next, we'll execute the search
WebElement searchField = driver.findElement(By.name("q"));
searchField.sendKeys(searchTerm);
WebElement searchButton = driver.findElement(By.name("btnK"));
searchButton.click();
// Now, let's gather our search results
List<WebElement> results = driver.findElements(By.cssSelector(".r"));
// Finally, we'll loop over the list to verify each result link contains our term
for (int i = 0; i < results.size(); i++) {
Assert.assertTrue(results.get(i).getText().contains(searchTerm), "Search result validation failed at instance [ + i + ].");
}
}
You may need to add any appropriate waits. This can also be further tweaked to ensure each result will be evaluated before a final pass/fail with a full output of each individual result that did not match the term, but I'll leave that to you to implement. Hopefully this will be a good start for you.
(by Arushi gupta、tim‑slifer)