繁体   English   中英

如何使用Selenium-Python从网站上项目的另一个目录上载图像?

[英]How do I upload an image from another directory of my project on web site with 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")

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

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

您好,快照中有一个id为“ image”的输入标签。 请尝试使用sendtext发送您愿意上传的图像的路径,然后单击“提交”将起作用。

代码应如下所示:

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

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

首先,有一个输入元素,您将键发送给该输入元素,而不是表单元素。 然后尝试不要单击输入元素,因为它将触发单击事件并打开硒无法处理的os文件检测器。

image_upload_input = wd.find_element_by_xpath("//*[@id='image']")
image_upload.send_keys(os.getcwd().replace("fixture", "") + "images/variant_1.png")

如果以某种方式发送密钥仍触发打开os文件检测器,则需要使用file_detector中的file_detector覆盖它:

from selenium.webdriver.remote.file_detector import UselessFileDetector
wd.file_detector = UselessFileDetector()

简而言之,整个代码将是:

from selenium.webdriver.remote.file_detector import UselessFileDetector
wd.file_detector = UselessFileDetector()
image_upload_input = wd.find_element_by_xpath("//*[@id='image']")
image_upload.send_keys(os.getcwd().replace("fixture", "") + "images/variant_1.png")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM