selenium文件上传和弹框处理
文件上传
input 标签可以直接使用send_keys(文件地址)上传文件
用法:
el = driver.find_element_by_id('上传按钮id')
el.send_keys("文件路径+文件名")
demo, 百度图片上传为例子
from base import *
class TestUpload(Base):
def test_upload(self):
url = 'https://image.baidu.com/'
self.driver.get(url)
self.driver.find_element_by_xpath("//img[@class='st_camera_off']").click()
self.driver.find_element_by_id("stfile").send_keys("D:\\my_project\\git_deve\\development\\img\\雪球自选设置测试用例.png") # 发送文件
time.sleep(3)
if __name__ == '__main__':
pytest.main(["-vs", "test_upload.py"])
弹框处理机制
操作alert常用方法:
- switch_to.alert(): 获取当前页面上的警告框
- text: 返回alert / confirm / prompt 中的文字系信息
- accept() : 接受现有警告框
- dismiss(): 解散现有警告框
- send_keys(KeysToSend) : 发送文本至警告框。 KeysToSend: 将文本发送至警告框
测试案例:
- 打开网页 https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable
- 操作窗口右侧页面,将元素1拖拽到元素2
- 这时候会有一个alert弹框,点击弹框中的确定
- 然后再按点击运行
- 关闭网页
from base import *
from selenium.webdriver import ActionChains
class TestUpload(Base):
@pytest.mark.skip
def test_upload(self):
url = 'https://image.baidu.com/'
self.driver.get(url)
self.driver.find_element_by_xpath("//img[@class='st_camera_off']").click()
self.driver.find_element_by_id("stfile").send_keys("D:\\my_project\\git_deve\\development\\img\\雪球自选设置测试用例.png") # 发送文件
time.sleep(3)
def test_la(self):
url = "https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable"
self.driver.get(url)
self.driver.switch_to.frame("iframeResult") # 可以参考 https://www.cnblogs.com/c-keke/p/14942162.html
draggable = self.driver.find_element_by_xpath("//div[@id='draggable']") # 拿起
droppable = self.driver.find_element_by_xpath("//div[@id='droppable']") # 放下
action = ActionChains(self.driver) # 初始化动作链, 可以参考:https://www.cnblogs.com/c-keke/p/14928477.html
action.drag_and_drop(draggable, droppable).pause(2).perform()
time.sleep(1)
self.driver.switch_to.alert.accept() # 点击确定这个弹出框
self.driver.switch_to.default_content() # 返回默认的节点
self.driver.find_element_by_xpath("//button[contains(text(),'点击运行')]").click()
if __name__ == '__main__':
pytest.main(["-vs", "test_upload.py"])
完。