web自动化测试以及常用元素定位方法

一、什么是Selenium

Selenium是一个用于web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。

参考文档:Selenium with Python中文翻译文档 — Selenium-Python中文文档 2 documentation

驱动下载:http://chromedriver.storage.googleapis.com/index.html

二、常用元素定位方法

  • 根据id定位

<html>
 <body>
  <form id="loginForm">
   <input name="username" type="text" />
   <input name="password" type="password" />
   <input name="continue" type="submit" value="Login" />
  </form>
 </body>
<html>

我们可以这样定位表单元素form

login_form = driver.find_element_by_id('loginForm')

  • 根据Name定位

<html>
 <body>
  <form id="loginForm">
   <input name="username" type="text" />
   <input name="password" type="password" />
   <input name="continue" type="submit" value="Login" />
   <input name="continue" type="button" value="Clear" />
  </form>
</body>
<html>

username和password元素,可以这样定位:

username = driver.find_element_by_name('username')
password = driver.find_element_by_name('password')

下面这个操作会返回Login按钮,因为它在Clear按钮的前面:

continue = driver.find_element_by_name('continue')

  • 根据XPath定位

<html>
 <body>
  <form id="loginForm">
   <input name="username" type="text" />
   <input name="password" type="password" />
   <input name="continue" type="submit" value="Login" />
   <input name="continue" type="button" value="Clear" />
  </form>
</body>
<html>

form元素可以这样定位:

login_form = driver.find_element_by_xpath("/html/body/form[1]")login_form = driver.find_element_by_xpath("//form[1]")login_form = driver.find_element_by_xpath("//form[@id='loginForm']")

  • 用链接文本定位超链接

<html>
 <body>
  <p>Are you sure you want to do this?</p>
  <a href="continue.html">Continue</a>
  <a href="cancel.html">Cancel</a>
</body>
<html>

可以这样定位continue.html链接:

continue_link = driver.find_element_by_link_text('Continue')
continue_link = driver.find_element_by_partial_link_text('Conti')

  • 标签名定位

知道元素标签名就使用这个定位,如果没有元素匹配,会抛出NoSuchElementException异常。

<html>
 <body>
  <h1>Welcome</h1>
  <p>Site content goes here.</p>
</body>
<html>

可以这样定位标题元素(h1):

heading1 = driver.find_element_by_tag_name('h1')

  • class定位

知道class就使用这个定位,只返回匹配的第一个,无元素匹配,会抛出NoSuchElementException异常。

<html>
 <body>
  <p class="content">Site content goes here.</p>
</body>
<html>

定位p元素:

content = driver.find_element_by_class_name('content')

  • css选择器定位

如果你能用css选择器的语法来表述一个元素,那么就选这个,只返回匹配的第一个,无元素匹配,会抛出NoSuchElementException异常。

<html>
 <body>
  <p class="content">Site content goes here.</p>
</body>
<html>

定位p元素:

content = driver.find_element_by_css_selector('.content')

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值