selenium python (七)层级定位(二次定位)

 

 

#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'zuoanvip'

#在实际测试过程中,一个页面可能有多个属性基本相同的元素,如果要定位到其中的一个,这时候需要用到层级定位。先定位到父元素,然后再通过父元素定位子孙元素

#导入包
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import  time
import os

driver = webdriver.Firefox()
#checkbox.html 要和脚本文件放一个目录下,否则需要指定checkbox.html的路径
file_path = 'file:///'+os.path.abspath('level_locate.html')
driver.get(file_path)

#首先定位到Link1链接(弹出下拉列表)
driver.find_element_by_id('xx').click()

#在父元素下找到link为Action的子元素
sub_element = driver.find_element_by_id('xx').find_element_by_link_text('Another_action')

#将鼠标移动到子元素上
ActionChains(driver).move_to_element(sub_element).perform()
time.sleep()

 

======================================================================================

level_locate页面源代码:

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Level Locate</title>
<script type="text/javascript" async="
" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css"
rel="stylesheet" />
</head>
<body>
<h3>Level locate</h3>
<div class="span3">
<div class="well">
<div class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Link1</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel" id="dropdown1" >
<li><a tabindex="-1" href="#">Action</a></li>
<li><a tabindex="-1" href="#">Another action</a></li>
<li><a tabindex="-1" href="#">Something else here</a></li>
<li class="divider"></li>
<li><a tabindex="-1" href="#">Separated link</a></li>
</ul>
</div>
</div>
</div>
<div class="span3">
<div class="well">
<div class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Link2</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel" >
<li><a tabindex="-1" href="#">Action</a></li>
<li><a tabindex="-1" href="#">Another action</a></li>
<li><a tabindex="-1" href="#">Something else here</a></li>
<li class="divider"></li>
<li><a tabindex="-1" href="#">Separated link</a></li>
</ul>
</div>
</div>
</div>
</body>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
</html>

发表评论

邮箱地址不会被公开。 必填项已用*标注