Java SeleniumWebDriver点击谷歌搜索
我正在谷歌主页上搜索“奶酪!”文本,不确定按下搜索按钮后如何点击搜索到的链接。例如,我想单击搜索页面顶部的第三个链接,然后如何查找、识别该链接并单击它。到目前为止,我的代码是:Java SeleniumWebDriver点击谷歌搜索,java,selenium,Java,Selenium,我正在谷歌主页上搜索“奶酪!”文本,不确定按下搜索按钮后如何点击搜索到的链接。例如,我想单击搜索页面顶部的第三个链接,然后如何查找、识别该链接并单击它。到目前为止,我的代码是: package mypackage; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.sup
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();
}
}
基于对GoogleWeb的快速检查,这将是页面列表中链接的CSS路径
ol[id=“rso”]h3[class=“r”]a
所以你应该做一些类似的事情
String path = "ol[id='rso'] h3[class='r'] a";
driver.findElements(By.cssSelector(path)).get(2).click();
但是,您也可以使用
xpath
,这并不是真正推荐的最佳实践,还可以使用JQuery定位器,但我不确定您是否可以在任何其他地方使用它们,除了在中,有多种方法可以找到元素(在您的情况下,是第三个Google搜索结果)
其中一种方法是使用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();
其他的选择是
By.ByClassName
By.ByCssSelector
By.ById
By.ByLinkText
By.ByName
By.ByPartialLinkText
By.ByTagName
为了更好地理解它们中的每一个,您应该尝试在比Google搜索结果页面更简单的地方学习Selenium
示例-
若要使用占位符“How can help?Ask here”与文本输入字段交互,请通过以下方式进行操作-
# 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!");
谷歌缩小了他们的css类等,所以不容易识别所有内容 你也有一个问题,你必须“等待”,直到网站显示结果。 我会这样做:
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"));
}
}
publicstaticvoidmain(字符串[]args){
WebDriver=newfirefoxdriver();
驱动程序。获取(“http://www.google.com");
WebElement=driver.findElement(By.name(“q”));
element.sendKeys(“Cheese!\n”);//同时发送一个“\n”
元素。提交();
//等待谷歌页面显示结果
WebElement myDynamicElement=(新的WebDriverWait(驱动程序,10))
。直到(预期条件。元素的存在(按.id(“结果状态”));
List findElements=driver.findElements(By.xpath(“//*[@id='rso']///h3/a”);
//这是你想访问的所有链接
for(WebElement WebElement:findElements)
{
System.out.println(webElement.getAttribute(“href”);
}
}
这将打印您:
@Test
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);
}
}
公开作废谷歌搜索()
{
网络驱动程序;
驱动程序=新的FirefoxDriver();
驱动程序。获取(“http://www.google.com");
driver.manage().window().maximize();
WebElement=driver.findElement(By.name(“q”));
元素。sendKeys(“Cheese!\n”);
元素。提交();
//等待谷歌页面显示结果
WebElement myDynamicElement=(新WebDriverWait(driver,10))。直到(ExpectedConditions.presenceOfElementLocated(By.id(“resultStats”));
List findElements=driver.findElements(By.xpath(“//*[@id='rso']///h3/a”);
//获取第三个链接的url并导航到它
字符串third_link=findElements.get(2.getAttribute)(“href”);
driver.navigate().到(第三个链接);
}
本页上的大多数答案都已过时。以下是一个更新的python版本,用于搜索google并获取所有结果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"\1", url, 0, re.IGNORECASE) # get the clean url
请注意,元素
id
/名称
/类
(@class='r'
)**将根据用户代理的不同而变化**。上面的代码使用了PhantomJS默认用户代理 这就是我得到的错误“类型的css(字符串)方法未定义为”欢迎使用堆栈溢出。你应该在你的答案中添加一个解释,描述你的代码如何帮助解决手头的问题,以及它是如何添加到先前发布的答案中的。我不确定这些评论是否被允许,但由于谷歌更新了它们的命名,该代码不再有效。您需要将“resultStats”替换为“result stats”
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"\1", url, 0, re.IGNORECASE) # get the clean url