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

一、寫在前面今天一實習生小孩問我,說哥你自動化學了多久才會的,咋學的?
【二 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這種寫法去寫,已經不支持老版本寫法 。
五、寫在最后相信大家和我一樣 , 基本都喜歡白嫖別人的教程,把珍藏多年的教程翻出來學了起來!
看到這,你肯定會說,六哥,你居然也這樣嗎,那是必然的?。?
細心點,你會發現,你收藏的教程或者學習視頻都過時了,對,你沒看錯,它就是過時了,!
雖然元素定位很簡單,但是細致很重要,光看不動手實踐,又怎么會發現問題呢?
我是六哥,如果覺得寫的還不錯,請繼續關注我 , 并幫忙轉發文章到朋友圈,你的每一次轉發,對我都很重要!

    推薦閱讀