首页 > 解决方案 > 如何使用 Selenium - Python 从网站上我的项目的另一个目录上传图像?

问题描述

我需要在网站上上传图片,我想将图片存储在我的项目中的单独目录“image”中,这样​​每个人都可以运行我的测试并上传图片而不会出现路径问题。

这是上传表单的html代码:

<form id="imageUploadForm" class="ant-form ant-form-horizontal image-upload-form">
<div class="ant-row ant-form-item">
<div class="ant-col ant-form-item-label ant-col-xs-24 ant-col-sm-4">
<label class="" title="Image list">Image list</label>
</div>
<div class="ant-col ant-form-item-control-wrapper ant-col-xs-24 ant-col-sm-16">
<div class="ant-form-item-control">
<span class="ant-form-item-children">
<div class="images-list">
<div class="images-list__upload-btn">
<span class="">
<div class="ant-upload ant-upload-select ant-upload-select-text">
<span tabindex="0" class="ant-upload" role="button">
<input id="image" type="file" accept="" style="display: none;">
<button type="button" class="ant-btn image-upload__btn">
<i aria-label="icon: plus" class="anticon anticon-plus">
<svg viewBox="64 64 896 896" class="" data-icon="plus" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false">

至于上传表格:网站上没有输入字段,您只能通过系统窗口选择文件。

这是我的代码:

import os

image_upload = wd.find_element_by_xpath("//*[@id='imageUploadForm']/div[1]/div[2]/div/span/div/div[1]/span/div")

// tap on a button which opens a system window
 image_upload.click()

//trying to send path to a file which stored in my project
image_upload.send_keys(os.getcwd().replace("fixture", "") + "images/variant_1.png")

显然,不起作用。还阅读了有关与“输入文件”交互的信息,但没有得到如何应用。

有任何想法吗?提前致谢!

标签: pythonselenium-webdriver

解决方案


您好,您的快照中有一个 id="image" 的输入标签。尝试使用 sendtext 发送您愿意上传的图片路径,然后单击提交即可。

代码应如下所示:

xpath ="//*[@id=\"image\"]; driver.FindElement(By.XPath(xpath)).SendKeys("Your image path");

然后在上传按钮上执行点击事件,它将起作用


推荐阅读