selenium-webdriver(python) (六) 操作測試對象

來源:互聯網
上載者:User

前面講到了不少知識都是定位元素,定位只是第一步,定位之後需要對這個原素進行操作。

滑鼠點擊呢還是鍵盤輸入,這要取決於我們定位的是按鈕還輸入框。

一般來說,webdriver中比較常用的操作對象的方法有下面幾個

· click 點擊對象

· send_keys 在對象上類比按鍵輸入

· clear 清除對象的內容,如果可以的話

在我們本系列開篇的第一個例子裡就用到了到click 和send_skys ,別翻回去找了,我再貼一下代碼:

# coding = utf-8from selenium import webdriver    browser = webdriver.Firefox()    browser.get("http://www.baidu.com")browser.find_element_by_id("kw").clear()browser.find_element_by_id("kw").send_keys("selenium")browser.find_element_by_id("su").click()browser.quit()

send_keys("XX")   用於在一個輸入框裡輸入內容。

click()   用於點擊一個按鈕。

clear()   用於清除輸入框的內容,比如百度輸入框裡預設有個“請輸入關鍵字”的資訊,再比如我們的登陸框一般預設會有“帳號”“密碼”這樣的預設資訊。clear可以協助我們清除這些資訊。

WebElement  另一些常用方法:

· text  擷取該元素的文本

· submit  提交表單

· get_attribute  獲得屬性值

text  

用於擷取元素的文本資訊

下面把百度首頁底部的聲明列印輸出

#coding=utf-8from selenium import webdriver    import  time    driver = webdriver.Firefox()driver.get("http://www.baidu.com")time.sleep(2)    #id = cp 元素的文本資訊data=driver.find_element_by_id("cp").textprint data   #列印資訊    time.sleep(3)driver.quit()

輸出:

>>>
2013 Baidu 使用百度前必讀 京ICP證030173號

submit

提交表單

我們把“百度一下”的操作從click 換成submit :

#coding=utf-8from selenium import webdriver    import time    driver = webdriver.Firefox()driver.get("http://www.baidu.com")    driver.find_element_by_id("kw").send_keys("selenium")time.sleep(2)#通過submit() 來操作driver.find_element_by_id("su").submit()      time.sleep(3)driver.quit()

這裡用submit 與click的效果一樣,我暫時還沒想到只能用submit 不能用click的情境。他們之間到底有啥區別,知道的同學請留言告訴我。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.