我正在尝试使用python和selenium在magento上自动执行产品上传,但是我在上传图片时遇到了问题。
我尝试用id="fileupload"
定位输入标签
driver.find_element_by_id("fileupload").send_keys('C:\\Users\\PC\\Desktop\\Code\\magento-bot\\image1.png')
似乎可行,因为当我将鼠标指针放在上传区域时,文件名会显示出来,但是提交后没有图像。
我也尝试过点击上传区域,然后选择要上传的文件:
uploadElement = driver.find_element_by_xpath('//html/body/div[2]/main/div[2]/div/div/div/div[2]/div[5]/div[2]/fieldset/div/div[2]/div[1]/div[1]/div[1]')
uploadElement.click()
driver.switch_to.active_element().send_keys(os.getcwd()+"\image1.png)
但我最终遇到此错误'FirefoxWebElement' object is not callable
最后,我尝试像这样模拟拖放:
element = os.getcwd()+"\image1.png"
target = bot.find_element_by_id('fileupload')
ActionChains(bot).drag_and_drop(element, target).perform
但是我得到下面的错误
AttributeError("move_to requires a WebElement")
任何帮助将不胜感激。
答案 0 :(得分:2)
可能是以下
的重复项JS_DROP_FILE = """
var target = arguments[0],
offsetX = arguments[1],
offsetY = arguments[2],
document = target.ownerDocument || document,
window = document.defaultView || window;
var input = document.createElement('INPUT');
input.type = 'file';
input.onchange = function () {
var rect = target.getBoundingClientRect(),
x = rect.left + (offsetX || (rect.width >> 1)),
y = rect.top + (offsetY || (rect.height >> 1)),
dataTransfer = { files: this.files };
['dragenter', 'dragover', 'drop'].forEach(function (name) {
var evt = document.createEvent('MouseEvent');
evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);
evt.dataTransfer = dataTransfer;
target.dispatchEvent(evt);
});
setTimeout(function () { document.body.removeChild(input); }, 25);
};
document.body.appendChild(input);
return input;
"""
def drag_and_drop_file(drop_target, path):
driver = drop_target.parent
file_input = driver.execute_script(JS_DROP_FILE, drop_target, 0, 0)
file_input.send_keys(path)
也请参见以下主题
Python with Selenium: Drag and Drop from file system to webdriver?
答案 1 :(得分:2)
我的问题的临时解决方案是AutoIt。
非常感谢@KunduK How to upload image with angular components using python selenium
我将图像上传区域的xpath作为目标,然后使用以下代码自动完成其余的操作:
autoit.win_wait_active("File Upload",5)
if autoit.win_exists("File Upload"):
autoit.control_send("File Upload","Edit1",filepath+"{ENTER}")```