警告框语法:switch_to.alert() : 定位;text:返回文字信息;accept():接受现有警告框;dismiss():解散现有警告框;send_keys():警告框输入文本。
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.find_element_by_id("s-usersetting-top").click()
driver.find_element_by_link_text("搜索设置").click()
time.sleep(2)
driver.find_element_by_link_text("保存设置").click()
alert = driver.switch_to.alert
alert_text = alert.text
print(alert_text)
alert.accept()
driver.quit()
"""
output:已经记录下您的使用偏好
"""
下拉框处理。语法:Select类:用于定位<select>标签;select_by_value():通过value值定位下拉选项;select_by_visible_text():通过text值定位下拉选项;
select_by_index():根据下拉选项的索引进行选择。第一个选项为0,第二个选项为1.
from selenium import webdriver import time from selenium.webdriver.support.select import Select driver = webdriver.Chrome() driver.get("https://www.baidu.com") driver.find_element_by_id("s-usersetting-top").click() driver.find_element_by_link_text("搜索设置").click() time.sleep(2) #搜索结果条数显示 sel = driver.find_element_by_xpath("//select[@id='nr']") #Value = 20 Select(sel).select_by_value("20") time.sleep(2) #<option>每页显示50条</option> Select(sel).select_by_visible_text("每页显示50条") time.sleep(2) #根据下拉选项的索引进行选择 Selecte(sel).select_by_index(0) time.sleep(2) driver.quit()