19.⽂件上传、弹框处理

发布时间 2023-12-29 13:56:04作者: 想要暴富的小男孩

⽂件上传的⾃动化

弹框处理机制

⽂件上传:

❖ input标签可以直接使⽤send_keys(⽂件地址)上传⽂件

❖ ⽤法:

❖ el = driver.find_element_by_id('上传按钮id')

❖ el.send_keys(”⽂件路径+⽂件名")

文件上传示例:

测试案例:

❖ 打开百度图⽚⽹址:https:// image.baidu.com

❖ 识别上传按钮

❖ 点击上传按钮

❖ 将本地的图⽚⽂件上传

chrome 开启 debug 模式:

有时候登录⽅式⽐较繁琐,需要动态⼿机密码,⼆维码登录之类的。⾃动话实现⽐较⿇烦。⼿⼯登录后, 不想让selenium启动⼀个新浏览器。可以使⽤chrome的debug⽅式来执⾏测试。

❖ 启动chrome的时候需要先退出所有chrome进程。使⽤ps aux|grep chrome|grep -v 'grep'查看是否有 chrome进程存在。确保没有chrome进程被启动过。下图是错误⽰范。

❖ 正常启动chrome的debug模式

❖ # 默认macOS系统

  ❖ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debuggingport=9222

❖ # Windows下找到chrome.exe位置执⾏下⾯的命令

  ❖ chrome.exe --remote-debugging-port=9222

❖ 启动后的提示信息,代表chrome运 ⾏正常,不要关闭⾃动打开的 chrome窗口。

弹框处理机制:

在页⾯操作中有时会遇到JavaScript所⽣成的alert、confirm以及prompt弹框,可以使⽤ switch_to.alert()⽅法定位到。然后使⽤text/accept/dismiss/send_keys等⽅法进⾏操作。参考教你 分辨alert、window、div模态框,以及操作:https://huilansame.github.io/

❖ 操作alert常⽤的⽅法:

  ❖ switch_to.alert():获取当前页⾯上的警告框。

  ❖ text:返回alert/confirm/prompt 中的⽂字信息。

  ❖ accept():接受现有警告框。

  ❖ dismiss():解散现有警告框。

  ❖ send_keys(keysToSend):发送⽂本⾄警告框。keysToSend:将⽂本发送⾄警告框。

alert窗⼜处理案例:

测试案例:

❖ 打开⽹页 https://www.runoob.com/ try/try.php?filename=jqueryui-apidroppable

❖ 操作窗⼜右侧页⾯, 将元素1拖拽到元素2

❖ 这时候会有⼀个alert弹框,点击弹框中的’ 确定’

❖ 然后再按’点击运⾏’

❖ 关闭⽹页

alert窗⼜处理案例:

def test_framedeal(self):

  self.driver.switch_to.frame("iframeResult")

  action = ActionChains(self.driver)

  action.click_and_hold(self.driver.find_element_by_id("draggable"))\

    .move_to_element(self.driver.find_element_by_id("droppable")).release().perform()

  self.driver.switch_to.alert.accept()

  # self.driver.switch_to.default_content()

  self.driver.switch_to.parent_frame()

  print(self.driver.find_element_by_id("submitBTN").text)

  self.driver.find_element_by_id("submitBTN").click()

  time.sleep(3)