selenium自动测试web页面

首先在官网下载chromedriver驱动,使用前先设置webdriver.chrome.driver值

@Before
public void setUp() {
    System.setProperty("webdriver.chrome.driver","D:\\tool\\chromedriver.exe");
    driver = new ChromeDriver();
}
@After
public void tearDown() {
    driver.quit();
}

chrome添加selenium ide插件,录制一下操作过程,然后导出成为java代码,然后在此基础上修改一下。

例如登录

public void login() throws InterruptedException {
    driver.get("网址");
    driver.manage().window().setSize(new Dimension(1564, 864));
    driver.findElement(By.id("inputusernma")).click();
    driver.findElement(By.id("inputusernma")).sendKeys("账号");
    driver.findElement(By.id("inputPassword3")).sendKeys("密码");
    driver.findElement(By.id("inputPassword3")).sendKeys(Keys.ENTER);
    driver.findElement(By.cssSelector(".item:nth-child(1) > .service")).click();
    Thread.sleep(3000);
    driver.findElement(By.cssSelector("div:nth-child(2) > .el-menu-item > span")).click();
}

selenium不可以在未访问当前域名的情况下设置cookie,这个是W3C标准。

遇到全站都需要登录才能访问,且登录页不在同一个域名内,那就只能先手动写代码登录了。

selenium 的mavn依赖

<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
    <artifactId>selenium</artifactId>
    <version>1.0-SNAPSHOT</version>
 
    <name>xx</name>
    <url>http://maven.apache.org</url>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
 
    <dependencies>
        <!-- 加载junit包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
 
        <!-- 加载selenium包 -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.9.1</version>
        </dependency>
    </dependencies>
</project>

通常选择web页面元素,要等页面加载完。selenium本身有等待页面加载的方法。

但是有把握的情况每步涉及网络请求的操作可以sleep一下就好了。

另外chrome f12 打开开发者页面,选源代码里面找到对应的element,然后右键copy,选择 css selector。就可以拿到元素定位了。

css selector比起xpath应该快一些。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值