0%

selenium

1. 浏览器配置

连接方式有 2 种:

  1. 使用本地驱动, 浏览器位于本机, 本机需要安装浏览器驱动 chromium-driver 或者 chrome-driver
1
2
// For use with ChromeDriver:
ChromeDriver driver = new ChromeDriver(options);
  1. 调用远程浏览器, 浏览器位于其他服务器上
1
2
3
4
// For use with RemoteWebDriver:
RemoteWebDriver driver = new RemoteWebDriver(
new URL("http://localhost:4444/wd/hub"),
new ChromeOptions());

1.1. ChromOptions

  1. addArguments
    通过 String 形式添加参数,如:
  • --no-sandbox 以root权限运行
  • --start-maximized 窗口最大化
  • --disable-extensions 禁止使用插件
  • --incognito 隐身模式 在浏览结束后, 会清除浏览记录(包括一些缓存文件)
  • --disable-plugins-discover 禁止发现扩展程序.
    在某些情况下, 网站通过检测扩展能够判断出是否为非法访问
  1. addEncodedExtensions
    添加编码插件
  2. addExtensions
    添加 crx 插件
  3. getExperimentalOption
  4. setAcceptInsecureCerts
    是否接受不安全的证书
  5. setBinary
    设置浏览器位置
  6. setExperimentalOption
    配置实验性参数, 如:
    禁止加载图片的配置:
1
2
3
4
Map<String, Object> prefs = new HashMap<String, Object>();
// 1: 允许 2: 不允许
prefs.put("profile.managed_default_content_settings.images", 2);
options.setExperimentalOption("prefs", prefs);
  1. setHeadless
    无界面运行
  2. setPageLoadStrategy
  3. setProxy
  4. setUnhandledPromptBehaviour

2. 测试样例

Selenium 测试view raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

/**
* @author raven
* @date 2018-07-02 20:45
*/
public class SeleniumTest {

@org.junit.Test
public void test() {
// Create a new instance of the Firefox driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new ChromeDriver();
// WebDriver driver = new HtmlUnitDriver(true);
// WebDriver driver = new FirefoxDriver();

// And now use this to visit Google
driver.get("https://www.baidu.com/");
// Alternatively the same thing can be done like this
// driver.navigate().to("http://www.google.com");

// Find the text input element by its name
WebElement element = driver.findElement(By.id("kw"));

// Enter something to search for
element.sendKeys("Cheese!");

// Now submit the form. WebDriver will find the form for us from the element
element.submit();

// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());

// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
}
});

// Should see: "cheese! - Google Search"
System.out.println("Page title is: " + driver.getTitle());

//Close the browser
driver.quit();
}
}