selenium-Locating Elements

There are vaious strategies to locate elements in a page. You can use the most appropriate one for your case. Selenium provides the following methods to locate elements in a page:

  • find_element_by_id
  • find_element_by_name
  • find_element_by_xpath
  • find_element_by_link_text
  • find_element_by_partial_link_text
  • find_element_by_tag_name
  • find_element_by_class_name
  • find_element_by_css_selector

To find multiple elements (these methods will return a list):

  • find_elements_by_name
  • find_elements_by_xpath
  • find_elements_by_link_text
  • find_elements_by_partial_link_text
  • find_elements_by_tag_name
  • find_elements_by_class_name
  • find_elements_by_css_selector

Apart from the public methods given above, there are two private methods which might be useful with locators in page objects. These are the two private methods: find_element and find_elements.

Example usage:

from selenium.webdriver.common.by import By

driver.find_element(By.XPATH, ‘//button[text()="Some text"]‘)
driver.find_elements(By.XPATH, ‘//button‘)

These are the attributes available for By class:

ID = "id"
XPATH = "xpath"
LINK_TEXT = "link text"
PARTIAL_LINK_TEXT = "partial link text"
NAME = "name"
TAG_NAME = "tag name"
CLASS_NAME = "class name"
CSS_SELECTOR = "css selector"

1.1. Locating by Id

Use this when you know id attribute of an element. With this strategy, the first element with the idattribute value matching the location will be returned. If no element has a matching id attribute, a NoSuchElementException will be raised.

For instance, consider this page source:

<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>

The form element can be located like this:

login_form = driver.find_element_by_id(‘loginForm‘)

1.2. Locating by Name

Use this when you know name attribute of an element. With this strategy, the first element with the name attribute value matching the location will be returned. If no element has a matching nameattribute, a NoSuchElementException will be raised.

For instance, consider this page source:

<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>

The username & password elements can be located like this:

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

This will give the “Login” button as it occur before the “Clear” button:

continue = driver.find_element_by_name(‘continue‘)

1.3. Locating by XPath

XPath is the language used for locating nodes in an XML document. As HTML can be an implementation of XML (XHTML), Selenium users can leverage this powerful language to target elements in their web applications. XPath extends beyond (as well as supporting) the simple methods of locating by id or name attributes, and opens up all sorts of new possibilities such as locating the third checkbox on the page.

One of the main reasons for using XPath is when you don’t have a suitable id or name attribute for the element you wish to locate. You can use XPath to either locate the element in absolute terms (not advised), or relative to an element that does have an id or name attribute. XPath locators can also be used to specify elements via attributes other than id and name.

Absolute XPaths contain the location of all elements from the root (html) and as a result are likely to fail with only the slightest adjustment to the application. By finding a nearby element with an id or name attribute (ideally a parent element) you can locate your target element based on the relationship. This is much less likely to change and can make your tests more robust.

For instance, consider this page source:

<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>

The form elements can be located like this:

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‘]")
  1. Absolute path (would break if the HTML was changed only slightly)
  2. First form element in the HTML
  3. The form element with attribute named id and the value loginForm

The username element can be located like this:

username = driver.find_element_by_xpath("//form[input/@name=‘username‘]")
username = driver.find_element_by_xpath("//form[@id=‘loginForm‘]/input[1]")
username = driver.find_element_by_xpath("//input[@name=‘username‘]")
  1. First form element with an input child element with attribute named name and the value username
  2. First input child element of the form element with attribute named id and the value loginForm
  3. First input element with attribute named ‘name’ and the value username

The “Clear” button element can be located like this:

clear_button = driver.find_element_by_xpath("//input[@name=‘continue‘][@type=‘button‘]")
clear_button = driver.find_element_by_xpath("//form[@id=‘loginForm‘]/input[4]")
  1. Input with attribute named name and the value continue and attribute named type and the value button
  2. Fourth input child element of the form element with attribute named id and value loginForm

These examples cover some basics, but in order to learn more, the following references are recommended:

There are also a couple of very useful Add-ons that can assist in discovering the XPath of an element:

  • XPath Checker - suggests XPath and can be used to test XPath results.
  • Firebug - XPath suggestions are just one of the many powerful features of this very useful add-on.
  • XPath Helper - for Google Chrome

1.4. Locating Hyperlinks by Link Text

Use this when you know link text used within an anchor tag. With this strategy, the first element with the link text value matching the location will be returned. If no element has a matching link text attribute, a NoSuchElementException will be raised.

For instance, consider this page source:

<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>

The continue.html link can be located like this:

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

1.5. Locating Elements by Tag Name

Use this when you want to locate an element by tag name. With this strategy, the first element with the given tag name will be returned. If no element has a matching tag name, a NoSuchElementException will be raised.

For instance, consider this page source:

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

The heading (h1) element can be located like this:

heading1 = driver.find_element_by_tag_name(‘h1‘)

1.6. Locating Elements by Class Name

Use this when you want to locate an element by class attribute name. With this strategy, the first element with the matching class attribute name will be returned. If no element has a matching class attribute name, a NoSuchElementException will be raised.

For instance, consider this page source:

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

The “p” element can be located like this:

content = driver.find_element_by_class_name(‘content‘)

1.7. Locating Elements by CSS Selectors

Use this when you want to locate an element by CSS selector syntaxt. With this strategy, the first element with the matching CSS selector will be returned. If no element has a matching CSS selector, a NoSuchElementException will be raised.

For instance, consider this page source:

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

The “p” element can be located like this:

content = driver.find_element_by_css_selector(‘p.content‘)

Sauce Labs has good documentation on CSS selectors.

时间: 2024-10-13 06:49:46

selenium-Locating Elements的相关文章

[Python爬虫] Selenium实现自动登录163邮箱和Locating Elements介绍

目录(?)[+] 前三篇文章介绍了安装过程和通过Selenium实现访问Firefox浏览器并自动搜索"Eastmount"关键字及截图的功能.而这篇文章主要简单介绍如何实现自动登录163邮箱,同时继续介绍Selenium+Python官网Locating Elements部分内容.        希望该篇基础性文章对你有所帮助,如果有错误或不足之处,请海涵~        [Python爬虫] 在Windows下安装PhantomJS和CasperJS及入门介绍(上)        

&lt;译&gt;Selenium Python Bindings 4 - Locating Eelements

有各种不同的策略来定位页面中的元素.你可以使用最合适定位方式用于你的用例.Selenium提供了以下方法来定位页面中的元素: find_element_by_id find_element_by_name find_element_by_xpath find_element_by_link_text find_element_by_partial_link_text find_element_by_tag_name find_element_by_class_name find_element_

[Python爬虫] Selenium自动访问Firefox和Chrome并实现搜索截图

前两篇文章介绍了安装,此篇文章算是一个简单的进阶应用吧!它是在Windows下通过Selenium+Python实现自动访问Firefox和Chrome并实现搜索截图的功能.        [Python爬虫] 在Windows下安装PhantomJS和CasperJS及入门介绍(上)        [Python爬虫] 在Windows下安装PIP+Phantomjs+Selenium 自动访问Firefox 可以参照前文安装Selenium环境,目前Selenium这个用于Web应用程序测试

[python爬虫] BeautifulSoup和Selenium对比爬取豆瓣Top250电影信息

这篇文章主要对比BeautifulSoup和Selenium爬取豆瓣Top250电影信息,两种方法从本质上都是一样的,都是通过分析网页的DOM树结构进行元素定位,再定向爬取具体的电影信息,通过代码的对比,你可以进一步加深Python爬虫的印象.同时,文章给出了我以前关于爬虫的基础知识介绍,方便新手进行学习.        总之,希望文章对你有所帮助,如果存在不错或者错误的地方,还请海涵~ 一. DOM树结构分析 豆瓣Top250电影网址:https://movie.douban.com/top2

selenium docs

Note to the Reader - Docs Being Revised for Selenium 2.0! Introduction Test Automation for Web Applications To Automate or Not to Automate? Introducing Selenium Brief History of The Selenium Project Selenium’s Tool Suite Choosing Your Selenium Tool S

[python爬虫] Selenium常见元素定位方法和操作的学习介绍

这篇文章主要Selenium+Python自动测试或爬虫中的常见定位方法.鼠标操作.键盘操作介绍,希望该篇基础性文章对你有所帮助,如果有错误或不足之处,请海涵~ 前文目录: [Python爬虫] 在Windows下安装PhantomJS和CasperJS及入门介绍(上) [Python爬虫] 在Windows下安装PIP+Phantomjs+Selenium [Python爬虫] Selenium自动访问Firefox和Chrome并实现搜索截图 [Python爬虫] Selenium实现自动登

[Python爬虫] Selenium爬取新浪微博移动端热点话题及评论 (下)

这篇文章主要讲述了使用python+selenium爬取新浪微博的热点话题和评论信息.其中使用该爬虫的缺点是效率极低,傻瓜式的爬虫,不能并行执行等,但是它的优点是采用分析DOM树结构分析网页源码并进行信息爬取,同时它可以通过浏览器进行爬取中间过程的演示及验证码的输入.这篇文章对爬虫的详细过程就不再论述了,主要是提供可运行的代码和运行截图即可.希望文章对你有所帮助吧~ 参考文章 [python爬虫] Selenium爬取新浪微博内容及用户信息 [Python爬虫] Selenium爬取新浪微博客户

[Python爬虫] Windows下Selenium自动访问Firefox和Chrome并实现搜索截图

前两篇文章介绍了安装,此篇文章算是一个简单的进阶应用吧!它是在Windows下通过Selenium+Python实现自动访问Firefox和Chrome并实现搜索截图的功能. [Python爬虫] 在Windows下安装PhantomJS和CasperJS及入门介绍(上) [Python爬虫] 在Windows下安装PIP+Phantomjs+Selenium 自动访问Firefox 可以参照前文安装Selenium环境,目前Selenium这个用于Web应用程序测试的工具支持的浏览器包括IE.

【RobotFramework】Selenium2Library类库关键字使用说明

Add CookieArguments:[ name | value | path=None | domain=None | secure=None | expiry=None ]Adds a cookie to your current session. "name" and "value" are required, "path", "domain" and "secure" are optional