【发布时间】:2018-09-11 22:59:38
【问题描述】:
设置
我正在使用 Python + Selenium 将图像上传到系统后端。
我send_keys()的上传按钮有以下HTML,
<div id="uploadifive-FileNameUpload" class="uploadifive-button" style="height:
18px; line-height: 18px; overflow: hidden; position: relative; text-align: center;
width: 50px;">
Upload
<input id="FileNameUpload" name="FileNameUpload" data-editor="#FileName"
data-url="http://also-inc.com/upload/uploadfile" data-path="~/UserFiles/Products/Images/"
data-maxsize="10240" data-extensions="*.jpg;*.jpeg;*.png;*.gif;*.bmp;"
data-thumbnailwidth="128" data-thumbnailheight="128"
data-thumbnailpath="/UserFiles/Products/Images/Preview/" data-uniquename="True"
data-preview="/Content/uploadify/noimage.jpg" data-isnew="true"
data-auth="D2C14774E29BBB87D2F34719884CFC5C6370502B067D5FC55D0C40A5EE6B1646ED4C77C9C0180D607052FF52653BA981732417A24C3F7547903649C4D64491C184E1C60D7756608784B4B3E806417E77750D87BABD9CDDCB6294EA62DE884EC7B3A4416558405874ED1C0259CD4430990BA83FC0"
data-session="f1txsiyxglqb3ma1dr45awrf" class="file-uploader hide-input" style="display: none;"
type="file">
<input style="font-size: 18px; opacity: 0; position: absolute; right: -3px; top: -3px; z-index: 999;" type="file">
</div>
请注意,该按钮有两个input 和type="file"。
使用的代码
upload_button = el_id('uploadifive-FileNameUpload').find_element_by_xpath('input[2]')
upload_button.send_keys(path_to_my_image)
其中el_id() = browser.find_element_by_id() 和path_to_my_image 以.jpeg 结尾。
问题
使用的代码通过第二个input成功上传图片。但是,图像保存时没有.jpeg 扩展名。因此图像在后端出现损坏;即image_name 而不是image_name.jpeg。
我认为图像是在没有扩展名的情况下保存的,因为第二个 input 不允许这样做。
尝试
- 将属性添加到第二个
input
第一个input 具有以下属性data-extensions="*.jpg;*.jpeg;*.png;*.gif;*.bmp;"。我将此属性添加到第二个input,
upload_button = el_id('uploadifive-FileNameUpload').find_element_by_xpath('input[2]')
browser.execute_script("arguments[0].setAttribute('data-extensions','*.jpg;*.jpeg;*.png;*.gif;*.bmp;')", upload_button)
upload_button = el_id('uploadifive-FileNameUpload').find_element_by_xpath('input[2]')
upload_button.send_keys(path_to_my_image)
这添加了属性,但上传的图像仍然保存,没有.jpeg 扩展名。
- 更改第一个
input的class和style属性
第一个input 有class="file-uploader hide-input" 和style="display: none;",我将它们设置为class="file-uploader" 和style="display: block;" via,
upload_button = el_id('uploadifive-FileNameUpload').find_element_by_xpath('input[1]')
browser.execute_script("arguments[0].setAttribute('class','file-uploader hide-input')", upload_button)
upload_button = el_id('uploadifive-FileNameUpload').find_element_by_xpath('input[1]')
browser.execute_script("arguments[0].setAttribute('style','display: block')", upload_button)
upload_button = el_id('uploadifive-FileNameUpload').find_element_by_xpath('input[1]')
upload_button.send_keys(path_to_my_image)
但是图片没有上传。上传按钮变为原生操作系统文件选择器“选择文件”按钮。
我该如何解决这个问题?
旁注
我不明白为什么这个按钮有两个input。我是初学者,如有错误请见谅,但直觉上我认为一个按钮只需要1个input?
【问题讨论】:
-
你说文件上传成功——只是没有扩展名。你到底在哪里看到的文件?名称的其余部分是否正确?也就是说,只是缺少扩展名吗?还有其他区别吗?例如,它是否与手动上传的其他文件位于同一文件夹中(即不使用 Selenium)?
-
可能是个愚蠢的问题,但您确定 path_to_my_image 包含文件扩展名吗?
标签: python image selenium upload