【Selenium6】下拉框、弹出框、滚动条操作
1、处理下拉框
所用HTML文档
<html> <body> <select id="ShippingMethod" onchange="updateShipping(options[selectedIndex]);" name="ShippingMethod"> <option value="12.51">UPS Next Day Air ==> $12.51</option> <option value="11.61">UPS Next Day Air Saver ==> $11.61</option> <option value="10.69">UPS 3 Day Select ==> $10.69</option> <option value="9.03">UPS 2nd Day Air ==> $9.03</option> <option value="8.34">UPS Ground ==> $8.34</option> <option value="9.25">USPS Priority Mail Insured ==> $9.25</option> <option value="7.45">USPS Priority Mail ==> $7.45</option> <option value="3.20" selected="">USPS First Class ==> $3.20</option> </select> </body> </html>
代码
coding=utf-8
from selenium import webdriver
import os
import time
driver=webdriver.Firefox()
file_path = 'file:///' + os.path.abspath('drop_down.html')
driver.get(file_path)
time.sleep(2)
m=driver.find_element_by_id('ShippingMethod') #定位到下拉框
m.find_element_by_xpath('//option[@value="10.69"]').click() #操作下拉框的选项
time.sleep(2)
browser.quit()
2、处理弹出框
使用switch_to_alert()方法定位到alert/confirm/prompt,然后进行text/accept/dismiss/sen_keys操作。text:返回文字信息、accept:点击确认按钮、dismiss:点击取消按钮、send_keys:向prompt中输入文字
coding=utf-8
from selenium import webdriver
import os
import time
driver=webdriver.Firefox()
driver.get('http://www.baidu.com')
driver.find_element_by_link_text('搜索设置').click() #进入搜索页面
m=driver.find_element_by_name('NR')
m.find_element_by_path('//option[@value="100"]').click() #设置每页搜索结果为100条
time.sleep(2)
driver.find_element_by_xpath('//input[@value="保存设置"]').click() #保存设置信息
time.sleep(2)
driver.seitch_to_alert().accept() #焦点集中与弹窗,并接受提示信息
driver.find_element_by_id('kw').send_keys('selenium')
driver.find_element_by_id('su').click()
time.sleep(2)
browser.quit()
3、处理滚动条
滚动条位置标识代码:
<body onload='document.body.scrollTop=0'> 滚动条在最上方
<body onload='document.body.scrollTop=100000'> 滚动条在最下方
代码1
js='var q=document.getElementById("id").scrollTop=100000' #适合内嵌窗口的场景,如法律条款
driver.execute_script(js)
代码2
coding=utf-8
from selenium import webdriver
import time
driver=webdriver.Firefox()
driver.get('http://www.baidu.com')
driver.find_element_by_id('kw').send_keys('selenium')
driver.find_element_by_id('su').click()
time.sleep(2)
js='var q=document.documentElement.scrollTop=100000' #将页面滚动条拖到底部
driver.execute_script(js)
time.sleep(2)
js='var q=document.documentElement.scrollTop=0' #将页面滚动条拖到顶部
driver.execute_script(js)
time.sleep(2)
browser.quit()