Selenium入门系列4 选择并操作一组元素

选中一组元素的方式也是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

driver=webdriver.Firefox()

driver.get('file:///F:/selenium/test.html')
#获取页面所有的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()

 

转载于:https://www.cnblogs.com/dinghanhua/p/9736398.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值