我正在搜索文本"奶酪!" 在谷歌主页上,不确定如何在按下搜索按钮后点击搜索到的链接.例如,我想在搜索页面上单击顶部的第三个链接,然后如何找到标识链接并单击它.我的代码到目前为止:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
d0x*_*d0x 27
谷歌缩小了他们的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"));
}
}
Run Code Online (Sandbox Code Playgroud)
这将打印出来:
| 归档时间: |
|
| 查看次数: |
93017 次 |
| 最近记录: |