Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏多维度架构

2.7. Java

2.7.1. Apple Mac 例子 Java 11 + Junit5 + Selenium + Safari

		
		
		
		

Maven 文件

			
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>cn.netkiller</groupId>
	<artifactId>selenium</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>selenium</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>11</maven.compiler.source>
		<maven.compiler.target>${maven.compiler.source}</maven.compiler.target>
		<junit.jupiter.version>5.4.0</junit.jupiter.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<version>${junit.jupiter.version}</version>
			<!-- <scope>test</scope> -->
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-params</artifactId>
			<version>${junit.jupiter.version}</version>
			<!-- <scope>test</scope> -->
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-engine</artifactId>
			<version>${junit.jupiter.version}</version>
			<!-- <scope>test</scope> -->
		</dependency>
		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-java</artifactId>
			<version>3.141.59</version>
		</dependency>
		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-safari-driver</artifactId>
			<version>3.141.59</version>
		</dependency>
	</dependencies>
	<build>
		<sourceDirectory>src</sourceDirectory>

		<plugins>
			<plugin>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>3.0.0-M3</version>
			</plugin>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.0</version>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>3.1.1</version>
				<configuration>
					<archive>
						<index>true</index>
						<manifest>
							<mainClass>demo.test</mainClass>
						</manifest>
					</archive>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
			
			
		
			
package cn.netkiller.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

/**
 * Hello world!
 *
 */
public class App {
	public static void main(String[] args) {
		System.out.println("Hello World!");
		WebDriver driver = new SafariDriver();
		driver.manage().window().setSize(new Dimension(1024, 768));
		driver.get("https://www.google.com.hk");
		driver.findElement(By.name("q")).sendKeys("webdriver");
		driver.findElement(By.name("btnK")).click();
		new WebDriverWait(driver, 3).until(ExpectedConditions.titleIs("webdriver - Google 搜尋"));
		driver.close();
	}
}
			
		

2.7.2. Windows Example

https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver

下载 https://sites.google.com/a/chromium.org/chromedriver/downloads

		
package cn.netkiller.webtest;

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;

/**
 * Hello world!
 *
 */
public class App {
	public static void main(String[] args) {
		System.out.println("Hello World!");

		// Create a new instance of the Firefox driver
		// Notice that the remainder of the code relies on the interface,
		// not the implementation.
		System.setProperty("webdriver.chrome.driver", "D:\\workspace\\chromedriver.exe");
		// WebDriver driver = new FirefoxDriver();
		WebDriver driver = new ChromeDriver();

		// And now use this to visit Google
		driver.get("http://www.google.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.name("q"));

		// 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();

	}
}
		
		

2.7.3. 获取信息

title
			
driver.getTitle();
			
			

当前 URL
			 
			WebDriver driver = new WebDriver();
			String url = driver.getCurrentUrl();			
			
			

2.7.4. 查找元素

			
		
		
By.id(String id);
			
By.className(String className);

			
By.cssSelector(String cssSelector);
			
String textFound = driver.findElement(By.cssSelector("h1")).getText();
			
			
By.linkText(String linkText);
			
By.partialLinkText(String partialLinkText);
			
			
			
			
By.name(String name);


			
By.tagName(String tagName);

			
By.xpath(String xpath);

			
getTagName()
			
String tagName = driver.findElement(By.id("email")).getTagName();
			
			
submit()
    		
driver.findElement(By.id("searchInput")).submit(); 
    		
			

2.7.5. 事件

填写信息
			
searchFieldElement.sendKeys("selenium tutorial javapointers.com");			
			
			
单击操作
			
WebElement searchButtonElement = webDriver.findElement(By.name("btnK"));
searchButtonElement.click();
			
			

2.7.6. 浏览器控制

窗口控制

最大化窗口

			
driver.manage().window().maximize();
			
			

指定分辨率

			
driver.manage().window().setSize(new Dimension(1024, 768));
			
			
切换窗口
			
	driver.switchTo().window(window);
			
			
超时
			
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);			
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
			
			
模拟手机浏览器

通过 options.addArguments 添加用户代理设置

			
EdgeOptions options = new EdgeOptions();
options.addArguments("--user-agent=iphone 8");
WebDriver driver = new EdgeDriver(options);	
			
			

方法二

		
//配置参数
Map<String, Object> deviceMetrics = new HashMap<String, Object>();

//设置屏幕大小、像素
deviceMetrics.put("width", 480);
deviceMetrics.put("height", 720);
deviceMetrics.put("pixelRatio", 3.0);

Map<String, Object> mobileEmulation = new HashMap<String, Object>();
mobileEmulation.put("deviceMetrics", deviceMetrics);

//设置要模拟的手机标识
mobileEmulation.put("userAgent",
		"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");

//声明ChromeOptions,主要是给chrome设置参数
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);

//设置驱动位置
System.setProperty("webdriver.chrome.driver", "D:\\Tools\\chromedriver.exe");
WebDriver driver = new ChromeDriver(chromeOptions);	
			
			
对话框

Alert
			
// for alert
        WebElement clickOnAlert = driver.findElement(By
                .xpath("//td/input[@name='alterbutton']"));
        clickOnAlert.click();
        delay(2);
        // get alert
        Alert alert = driver.switchTo().alert();
        Assert.assertTrue(alert.getText().contains("alert"));
        // click alert ok
        alert.accept();
			
				
输入对话框
			
// for prompt
        WebElement clickOnPrompt = driver.findElement(By
                .xpath("//td/input[@name='promptbutton']"));
        clickOnPrompt.click();
        delay(2);
        Alert prompt = driver.switchTo().alert();

        prompt.sendKeys("I love Selenium");
        prompt.accept();
        delay(5);
        Alert afterAccept = driver.switchTo().alert();
        Assert.assertTrue(afterAccept.getText().contains("I love Selenium"));
        // click alert ok
        afterAccept.accept();	
			
				
确认对话框
				
		// for confirm
        WebElement clickOnConfirm = driver.findElement(By
                .xpath("//td/input[@name='confirmbutton']"));
        clickOnConfirm.click();
        delay(2);
        Alert confirm = driver.switchTo().alert();
        confirm.dismiss();
        delay(2);
        Alert afterDismiss = driver.switchTo().alert();
        Assert.assertTrue(afterDismiss.getText().contains("You pressed Cancel"));
        delay(2);
        afterDismiss.accept();
			
				

2.7.7. 等待

等待显示
			
		/*Get the text after ajax call*/
		WebDriverWait wait = new WebDriverWait(driver, 5);
		WebElement TextElement = driver.findElement(By.className("radiobutton"));
		wait.until(ExpectedConditions.visibilityOf(TextElement));
		String textAfter = TextElement.getText().trim();			
		
显式等待

显式等待 使用ExpectedConditions类中自带方法, 可以进行显试等待的判断。

显式等待可以自定义等待的条件,用于更加复杂的页面等待条件


等待的条件

WebDriver方法

页面元素是否在页面上可用和可被单击

elementToBeClickable(By locator)

页面元素处于被选中状态

elementToBeSelected(WebElement element)

页面元素在页面中存在

presenceOfElementLocated(By locator)

在页面元素中是否包含特定的文本

textToBePresentInElement(By locator)

页面元素值

textToBePresentInElementValue(By locator, java.lang.String text)

标题 (title)

titleContains(java.lang.String title)		
			
			
等待输入密码
			
WebDriverWait wait=new WebDriverWait(webDriver,5);
wait.until(ExpectedConditions.elementToBeClickable(By.id("name"))).sendKeys("用户名");

			
			
			

2.7.8. 等待页面

		 
		driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(12));

		driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(12));

		driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(10));
		
		WebElement res = new WebDriverWait(driver, Duration.ofSeconds(15))
        .until(ExpectedConditions.elementToBeClickable(By.xpath(“//a/h1”)));		
		
		

2.7.9. HTML 表单处理

SELECT
		
	WebElement selector = driver.findElement(By.id("Selector"));
	Select select = new Select(selector);
	select.selectByIndex(2);
	select.selectByVisibleText("苹果");
	select.selectByValue("apple");