Selenium入門系列4 選擇並操作一組元素
阿新 • • 發佈:2018-10-02
selenium num lec 點擊 doctype img web selector mage
選中一組元素的方式也是8種,與選中單個元素一一對應。區別只在於element與elements。elements取到的是一個數組,element取符合條件的第一個元素。
首先在腳本的目錄下新建test.html文件,將下面的內容拷貝進去保存。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>測試頁面</title> </head> <body> <form action="" style="font-size: 30px;color:#00ccff;"> <input type="checkbox">check1<br> <input type="checkbox">check2<br> <input type="checkbox">check3<br> <input type="checkbox">check4<br> <input type="checkbox">check5<br> </form> <hr> <form action="" style="font-size: 30px;color:#cc00ff;"> <input type="radio" name>radio1<br> <input type="radio" name>radio2<br> <input type="radio" name>radio3<br> </form> </body> </html>
編寫腳本python腳本
#coding=utf-8 #獲取一組元素,再循環操作 from selenium import webdriver import time import os driver=webdriver.Firefox() filepath="file:///" +os.path.abspath("test.html") #打開示例頁面 driver.get(filepath) #獲取頁面所有的input,再判斷是否是復選框,選中所有復選框 inputs=driver.find_elements_by_tag_name("input") for inputtag in inputs: if inputtag.get_attribute("type") == "checkbox": inputtag.click() time.sleep(0.5) #獲取頁面所有的復選框,去掉勾選 checkboxes = driver.find_elements_by_css_selector("input[type=checkbox]") print(‘the num of checkbox is ‘,len(checkboxes))#復選框個數 for checkbox in checkboxes: checkbox.click() #點擊最後一個單選框 driver.find_elements_by_css_selector("input[type=radio]").pop().click() #點擊第二個checkbox driver.find_elements_by_css_selector("input[type=checkbox]")[1].click() time.sleep(2) driver.quit()
Selenium入門系列4 選擇並操作一組元素