1.单选按钮:
(1)首先定位单选按钮的位置。
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
time.sleep(2)
link = driver.find_element_by_id("s-usersetting-top").click()
driver.find_element_by_link_text("搜索设置").click()
time.sleep(3)
#单选按钮
abc = driver.find_element_by_id("nr_2")
#保存设置
driver.find_element_by_class_name("prefpanelgo").click()
alert = driver.switch_to.alert
print(alert.text)
#接受弹框
alert.accept()
driver.quit()
2、===============复选框==============
(1)选中/取消一个复选框
(2)选中/取消所有复选框
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://baike.baidu.com/")
#点击:登录按钮
driver.find_element_by_xpath("//*[@id='j-wgt-userbar']/li[2]/a").click()
time.sleep(6)
#选中用户登录方式
driver.find_element_by_xpath("//*[@id='TANGRAM__PSP_11__footerULoginBtn']").click()
time.sleep(6)
#输入账号、密码,进行登录
driver.find_element_by_id("TANGRAM__PSP_11__userName").send_keys("********")
driver.find_element_by_id("TANGRAM__PSP_11__password").send_keys("*********")
driver.find_element_by_id("TANGRAM__PSP_11__submit").click()
time.sleep(6)
#设置
driver.find_element_by_xpath("//*[@id='j-wgt-userbar']/li[5]/a").click()
driver.find_element_by_link_text("消息设置").click()
time.sleep(6)
#进入消息设置页面
driver.get("https://baike.baidu.com/usercenter/settings#message")
time.sleep(2)
#选中/取消一个复选框
driver.find_element_by_xpath("//*[@id='second']").click()
#选中/取消所有复选框
checkboxs = driver.find_element_by_xpath("//*[@type='checkbox]")
for iin checkboxs:
if i.get_attribute('type') =="checkbox":
i.click()
#driver.find_element_by_xpath("//*[@type='checkbox]").pop().click()
#点击保存
driver.find_element_by_xpath("/html/body/dl/dd/dl/dd/ul/li[2]/div/a").click()
driver.quit()
3、is_selected()方法用来检查是否选中该元素,一般针对单选按钮、复选框,其返回的结果是Bool值。通过is_selected()方法先检查复选框是否被选中,如被选中则结束代码运行,如未被选中则执行选中操作。用法如下:
selected_true = driver.find_element_by_xpath("//*[@id='second']").is_selected()
if selected_true == True:
print(selected_true)
else:
driver.find_element_by_xpath("//*[@id='second']").click()
4、下拉列表框:
driver.get("https://www.baidu.com/")
driver.find_element_by_id("s-usersetting-top").click()
driver.find_element_by_link_text("高级搜索").click()
time.sleep(5)
#下拉列表
driver.find_element_by_xpath("//*[@id='adv-setting-gpc']/div").click()
#选中指定一个下拉列表的值
driver.find_element_by_xpath("//*[@id='adv-setting-gpc']/div/div[2]/div[2]/p[2]").click()
driver.find_element_by_xpath("//*[@id='wrapper']/div[6]/span").click()
driver.quit()