软件自动化测试

Time: 2024-09-23 Monday 20:23:01
Author: Jackasher

软件自动化测试

本来不想做了,结果最后成功了,版本一直是对的,只是chrome有跨域问题

![image-20240920003914754](/Users/leojackasher/Library/Application Support/typora-user-images/image-20240920003914754.png)

尽管如此还是有报错,但是这不影响运行 !!!只要接着往下写,就可以运行

image-20240920003945544

下面是源码,注意打开新窗口是要切换到新窗口选取元素,同时今天知道了浏览器可以获取Xpath和Selector,还有JS路径,太方便了

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package org.example;

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.chrome.ChromeOptions;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
* @ClassName: BaiduSearch
* @author: LiShuai
* @create: 2021-07-12 15:14
**/
public class BaiduSearch {
/**
* 访问的目标地址
*/
private static final String URL = "https://shop.aircheng.com/";

public static void test() throws InterruptedException {

// 设置 ChromeDriver 路径
System.setProperty("webdriver.chrome.driver", "/Users/leojackasher/Download/Compressed/chromedriver-mac-arm64 3/chromedriver");

ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
options.setBinary("/Users/leojackasher/Download/Compressed/chrome-mac-arm64 2/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing");

// 定义驱动对象为 ChromeDriver
WebDriver driver = new ChromeDriver(options);

// 打开目标网站
driver.get(URL);

// 隐式等待,确保页面元素加载完成
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// 找到并点击第一个元素
WebElement firstElement = driver.findElement(By.xpath("/html/body/header/div[2]/div/div/div[1]/ul/li[1]/div[1]/a[1]"));
firstElement.click();

// 等待几秒钟以确保页面加载
Thread.sleep(2000);

// 找到并点击第二个元素
WebElement secondElement = driver.findElement(By.xpath("/html/body/div[3]/div/section[2]/section/section/ul/li[1]/a"));
secondElement.click();

// 等待几秒钟以确保页面加载
Thread.sleep(2000);

// 记录当前窗口句柄
String originalWindow = driver.getWindowHandle();

// 获取所有窗口句柄
Set<String> handles = driver.getWindowHandles();

// 找到并切换到新窗口
for (String handle : handles) {
if (!handle.equals(originalWindow)) {
driver.switchTo().window(handle);
break;
}
}

// 在新窗口中找到并点击第三个元素
WebElement thirdElement = driver.findElement(By.xpath("/html/body/div[3]/div/section[2]/section[2]/div[2]/div[1]/span"));
thirdElement.click();

// 等待几秒钟以确保操作完成
Thread.sleep(2000);

// 关闭新窗口
driver.close();

// 切换回原窗口
driver.switchTo().window(originalWindow);

// 继续在原窗口中执行操作
// 可以在这里添加更多的操作代码

// 关闭驱动
driver.quit();
}

public static void main(String[] args) throws InterruptedException {
test();
}
}


软件自动化测试
http://example.com/2024/09/23/软件自动化测试/
作者
Jack Asher
发布于
2024年9月23日
许可协议