Last active
May 30, 2023 19:32
-
-
Save danbao/25645c0648e6a0d3a4ea to your computer and use it in GitHub Desktop.
Selenium For Chrome : Open Chrome and Search linzhen@net
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Selenium.start; | |
import java.io.File; | |
import java.io.IOException; | |
import org.openqa.selenium.By; | |
import org.openqa.selenium.WebDriver; | |
import org.openqa.selenium.WebElement; | |
import org.openqa.selenium.chrome.ChromeDriverService; | |
import org.openqa.selenium.remote.DesiredCapabilities; | |
import org.openqa.selenium.remote.RemoteWebDriver; | |
import org.openqa.selenium.support.ui.ExpectedCondition; | |
import org.openqa.selenium.support.ui.WebDriverWait; | |
public class SeleniumForChrome { | |
public static void main(String[] args) throws IOException { | |
// 设置 chrome 的路径 | |
// System.setProperty( | |
// "webdriver.chrome.driver", | |
// "C:\\Documents and Settings\\sq\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe"); | |
// 创建一个 ChromeDriver 的接口,用于连接 Chrome | |
ChromeDriverService service = new ChromeDriverService.Builder() | |
.usingDriverExecutable( | |
new File( | |
"D:\\Dropbox\\SourceCode\\webdriver\\chromedriver.exe")) | |
.usingAnyFreePort().build(); | |
service.start(); | |
// 创建一个 Chrome 的浏览器实例 | |
WebDriver driver = new RemoteWebDriver(service.getUrl(), | |
DesiredCapabilities.chrome()); | |
// 让浏览器访问 hao123 | |
driver.get("http://www.hao123.com"); | |
// 用navigate方法,然后再调用to方法 | |
driver.navigate().to("http://www.baidu.com"); | |
// 获取 网页的 title | |
System.out.println("1 Page title is: " + driver.getTitle()); | |
// 通过 id 找到 input 的 DOM | |
WebElement element = driver.findElement(By.id("kw")); | |
// 输入关键字 | |
element.sendKeys("linzhen@net"); | |
// 提交 input 所在的 form | |
element.submit(); | |
// 通过判断 title 内容等待搜索页面加载完毕,间隔10秒 | |
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { | |
public Boolean apply(WebDriver d) { | |
return d.getTitle().toLowerCase().contains("linzhen@net"); | |
} | |
}); | |
// 显示搜索结果页面的 title | |
System.out.println("2 Page title is: " + driver.getTitle()); | |
// 关闭浏览器 | |
driver.quit(); | |
// 关闭 ChromeDriver 接口 | |
service.stop(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment