天天看點

Selenium+Python系列(二) - 元素定位那些事

一、寫在前面

今天一實習生小孩問我,說哥你自動化學了多久才會的,咋學的?

自學三個月吧,真的是硬磕呀,當時沒人給講😅!

其實,學什麼都一樣,真的就是你想改變的決心有多強罷了。

二、元素定位

這部分内容可以說是重中之重了,也是大部分寫​

​web​

​自動化的同學,必會入門技能之一了。

1、常見八種定位元素方法

我們還是直接來看源代碼吧,示例如下:

# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

"""
The By implementation.
"""


class By:
    """
    Set of supported locator strategies.
    """

    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"      

2、根據id定位元素

​driver.find_element(By.ID,"kw")​

3、根據xpath定位元素

​driver.find_element(By.XPATH, '//*[@id="kw"]')​

4、根據css定位器定位元素

​driver.find_element(By.CSS_SELECTOR, '#kw')​

5、根據name屬性值定位元素

​driver.find_element(By.NAME, 'wd')​

6、根據class_name類名定位元素

​driver.find_element(By.CLASS_NAME, 's_ipt')​

7、根據連結文本定位元素

​driver.find_element(By.LINK_TEXT, 'hao123')​

8、根據部分連結文本定位元素

​driver.find_element(By.PARTIAL_LINK_TEXT, 'hao')​

9、根據标簽名定位元素

​driver.find_element(By.TAG_NAME, 'input')​

三、find_element與find_elements差別

  • find_elemnet:定位到是一個對象,定位不到則報錯。
  • find_elemnets:定位到是一個含元素的清單,定位不到是一個空清單。

四、值得關注的問題

1、舉個栗子

# 這句運作直接報錯
driver.find_element_by_id('kw').send_keys('python')
# 這句就正常
driver.find_element(By.ID,"kw").send_keys(u"久曲健 部落格園")      

2、為什麼報錯

來吧,還是直接看源代碼學習,如下所示:

Selenium+Python系列(二) - 元素定位那些事

不難看出,最新版本隻能通過find這種寫法去寫,已經不支援老版本寫法。

五、寫在最後

相信大家和我一樣,基本都喜歡白嫖别人的教程,把珍藏多年的教程翻出來學了起來!

看到這,你肯定會說,六哥,你居然也這樣嗎,那是必然的!!

細心點,你會發現,你收藏的教程或者學習視訊都過時了,對,你沒看錯,它就是過時了,😂!

雖然元素定位很簡單,但是細緻很重要,光看不動手實踐,又怎麼會發現問題呢?

我是六哥,如果覺得寫的還不錯,請繼續關注我,并幫忙轉發文章到朋友圈,你的每一次轉發,對我都很重要!🙏

優秀不夠,你是否無可替代

軟體測試交流QQ群:721256703,期待你的加入!!

歡迎關注我的微信公衆号:軟體測試君

Selenium+Python系列(二) - 元素定位那些事