Java Selenium webdriver 点击谷歌搜索
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18387598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selenium webdriver click google search
提问by min2bro
I'm searching text "Cheese!" on google homepage and unsure how can I can click on the searched links after pressing the search button. For example I wanted to click the third link from top on search page then how can I find identify the link and click on it. My code so far:
我正在搜索文本“奶酪!” 在谷歌主页上,不确定如何在按下搜索按钮后点击搜索到的链接。例如,我想单击搜索页面顶部的第三个链接,然后如何找到识别链接并单击它。到目前为止我的代码:
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class myclass {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\selenium-java-2.35.0\chromedriver_win32_2.2\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("Cheese!");
element.submit();
//driver.close();
}
}
采纳答案by d0x
Google shrinks their css classes etc., so it is not easy to identify everything.
谷歌缩小了他们的css类等,所以不容易识别所有的东西。
Also you have the problem that you have to "wait" until the site shows the result. I would do it like this:
你也有问题,你必须“等待”,直到网站显示结果。我会这样做:
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("Cheese!\n"); // send also a "\n"
element.submit();
// wait until the google page shows the result
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));
List<WebElement> findElements = driver.findElements(By.xpath("//*[@id='rso']//h3/a"));
// this are all the links you like to visit
for (WebElement webElement : findElements)
{
System.out.println(webElement.getAttribute("href"));
}
}
This will print you:
这将打印您:
- http://de.wikipedia.org/wiki/Cheese
- http://en.wikipedia.org/wiki/Cheese
- http://www.dict.cc/englisch-deutsch/cheese.html
- http://www.cheese.com/
- http://projects.gnome.org/cheese/
- http://wiki.ubuntuusers.de/Cheese
- http://www.ilovecheese.com/
- http://cheese.slowfood.it/
- http://cheese.slowfood.it/en/
- http://www.slowfood.de/termine/termine_international/cheese_2013/
- http://de.wikipedia.org/wiki/Cheese
- http://en.wikipedia.org/wiki/Cheese
- http://www.dict.cc/englisch-deutsch/cheese.html
- http://www.cheese.com/
- http://projects.gnome.org/cheese/
- http://wiki.ubuntuusers.de/Cheese
- http://www.ilovecheese.com/
- http://cheese.slowfood.it/
- http://cheese.slowfood.it/en/
- http://www.slowfood.de/termine/termine_international/cheese_2013/
回答by Petr Mensik
Based on quick inspection of google web, this would be CSS path to links in page list
基于对 google web 的快速检查,这将是页面列表中链接的 CSS 路径
ol[id="rso"] h3[class="r"] a
ol[id="rso"] h3[class="r"] a
So you should do something like
所以你应该做类似的事情
String path = "ol[id='rso'] h3[class='r'] a";
driver.findElements(By.cssSelector(path)).get(2).click();
However you could also use xpath
which is not really recommended as a best practice and also JQuery locators but I am not sure if you can use them aynywhere else except inArquillian Graphene
但是,您也可以使用xpath
which 不是真正推荐的最佳实践以及 JQuery 定位器,但我不确定您是否可以在除Arquillian Graphene之外的任何其他地方使用它们
回答by Amey
There would be multiple ways to find an element (in your case the third Google Search result).
有多种方法可以找到一个元素(在您的情况下是第三个 Google 搜索结果)。
One of the ways would be using Xpath
其中一种方法是使用 Xpath
#For the 3rd Link
driver.findElement(By.xpath(".//*[@id='rso']/li[3]/div/h3/a")).click();
#For the 1st Link
driver.findElement(By.xpath(".//*[@id='rso']/li[2]/div/h3/a")).click();
#For the 2nd Link
driver.findElement(By.xpath(".//*[@id='rso']/li[1]/div/h3/a")).click();
The other options are
其他选项是
By.ByClassName
By.ByCssSelector
By.ById
By.ByLinkText
By.ByName
By.ByPartialLinkText
By.ByTagName
To better understand each one of them, you should try learning Selenium on something simpler than the Google Search Result page.
为了更好地理解它们中的每一个,您应该尝试在比 Google 搜索结果页面更简单的东西上学习 Selenium。
Example - http://www.google.com/intl/gu/contact/
示例 - http://www.google.com/intl/gu/contact/
To Interact with the Text input field with the placeholder "How can we help? Ask here." You could do it this way -
使用占位符“我们如何提供帮助?在此处询问”与文本输入字段交互。你可以这样做 -
# By.ByClassName
driver.findElement(By.ClassName("searchbox")).sendKeys("Hey!");
# By.ByCssSelector
driver.findElement(By.CssSelector(".searchbox")).sendKeys("Hey!");
# By.ById
driver.findElement(By.Id("query")).sendKeys("Hey!");
# By.ByName
driver.findElement(By.Name("query")).sendKeys("Hey!");
# By.ByXpath
driver.findElement(By.xpath(".//*[@id='query']")).sendKeys("Hey!");
回答by Anand
Simple Xpath for locating Google search box is: Xpath=//span[text()='Google Search']
用于定位 Google 搜索框的简单 Xpath 是:Xpath=//span[text()='Google Search']
回答by Anand
public class GoogleSearch {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://www.google.com");
driver.findElement(By.xpath("//input[@type='text']")).sendKeys("Cheese");
driver.findElement(By.xpath("//button[@name='btnG']")).click();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("(//h3[@class='r']/a)[3]")).click();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
}
}
回答by Mahesh Sutar
@Test
public void google_Search()
{
WebDriver driver;
driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.manage().window().maximize();
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("Cheese!\n");
element.submit();
//Wait until the google page shows the result
WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));
List<WebElement> findElements = driver.findElements(By.xpath("//*[@id='rso']//h3/a"));
//Get the url of third link and navigate to it
String third_link = findElements.get(2).getAttribute("href");
driver.navigate().to(third_link);
}
回答by CONvid19
Most of the answers on this page are outdated.
Here's an updated python version to search google and get all results href's:
此页面上的大多数答案已过时。
这是一个更新的python版本,用于搜索谷歌并获取所有结果href:
import urllib.parse
import re
from selenium import webdriver
driver.get("https://google.com/")
q = driver.find_element_by_name('q')
q.send_keys("always look on the bright side of life monty python")
q.submit();
sleep(1)
links= driver.find_elements_by_xpath("//h3[@class='r']//a")
for link in links:
url = urllib.parse.unquote(webElement.get_attribute("href")) # decode the url
url = re.sub("^.*?(?:url\?q=)(.*?)&sa.*", r"", url, 0, re.IGNORECASE) # get the clean url
Please note that the element id
/name
/class
(@class='r'
) ** will change depending on the user agent**.
The above code used PhantomJSdefault user agent.
请注意,元素id
/ name
/ class
(@class='r'
)**将根据用户代理更改**。
上面的代码使用了PhantomJS默认的用户代理。