2

Estoy usando Selenium y Python, y me he encontrado con este problema. Tengo que subir una imagen al servidor y no veo la forma.

El código HTML es este.

<a id="file_upload" href="javascript:;">Añadir imágenes</a>

Cuando se hace click en este link se abre la típica ventana del sistema para seleccionar archivos.

Por el momento lo único que he logrado hacer es localizar el elemento y hacer click en él.

 img_upload = driver.find_element_by_id("file_upload")
 img_upload .click()

Tabién he probado así pero no pasa nada

img_upload = driver.find_element_by_id("file_upload")
img_upload.send_keys(img_path)

¿Alguna ídea de como poder subir la imagen?


Bueno, ya sé que lo ésto es una locura porque está codificado... pero es el fragmento de código de JavaScript que controla lo de subir el archivo... Lo pongo por si sirviera de algo.

function s() {
    var e, s;
    i.extend(this, {
        init: function(u) {
            var c, l, d, m, h, f, p = this,
                g = p.getRuntime();

            e = u, d = o.extList2mimes(e.accept, g.can("filter_by_extension")),
                l = g.getShimContainer(),

                l.innerHTML = '<input id="' + g.uid + '" type="file" style="font-size:999px;
            opacity: 0;
            "'+(e.multiple&&g.can("
            select_multiple ")?"
            multiple ":"
            ")+               
            (e.directory && g.can("select_folder") ?
                "webkitdirectory directory" : "") +
            (d ? ' accept="' + d.join(",") + '"' : "") + " />",
            c = n.get(g.uid), i.extend(c.style,

                    {
                        position: "absolute",
                        top: 0,
                        left: 0,
                        width: "100%",
                        height: "100%"
                    }), m = n.get(e.browse_button), s = n.getStyle(m, "z-index") || "auto", g.can("summon_file_dialog") && ("static" === n.getStyle(m, "position") &&

                    (m.style.position = "relative"), r.addEvent(m, "click", function(e) {
                        var t = n.get(g.uid);
                        t && !t.disabled &&

                            t.click(), e.preventDefault()
                    }, p.uid), p.bind("Refresh", function() {
                        h = parseInt(s, 10) || 1, n.get(e.browse_button).style.zIndex = h, this.getRuntime().getShimContainer().style.zIndex = h - 1
                    })), f = g.can("summon_file_dialog") ? m : l, r.addEvent(f, "mouseover", function()

                    {
                        p.trigger("mouseenter")
                    }, p.uid), r.addEvent(f, "mouseout", function()

                    {
                        p.trigger("mouseleave")
                    }, p.uid), r.addEvent(f, "mousedown", function()

                    {
                        p.trigger("mousedown")
                    }, p.uid), r.addEvent(n.get(e.container), "mouseup", function() {
                    p.trigger("mouseup")
                }, p.uid),

                (g.can("summon_file_dialog") ? c : m).setAttribute("tabindex", -1), c.onchange = function x() {
                    if (p.files = [], i.each(this.files, function(i) {
                            var n = "";
                            return e.directory && "." == i.name ? !0 : (i.webkitRelativePath && (n = "/" + i.webkitRelativePath.replace(/^\//, "")), i = new t(g.uid, i), i.relativePath = n, p.files.push(i), void

                                0)
                        }), "IE" !== a.browser && "IEMobile" !== a.browser) this.value = "";
                    else {
                        var n = this.cloneNode(!0);

                        this.parentNode.replaceChild(n, this), n.onchange = x
                    }
                    p.files.length && p.trigger("change")
                }, p.trigger({
                    type: "ready",
                    async: !0
                }), l = null
        },
        setOption: function(e, t) {
            var i = this.getRuntime(),
                r = n.get(i.uid);
            switch (e) {
                case "accept":
                    if (t) {
                        var

                            a = t.mimes || o.extList2mimes(t, i.can("filter_by_extension"));
                        r.setAttribute("accept", a.join(","))
                    } else

                        r.removeAttribute("accept");
                    break;
                case "directory":
                    t && i.can("select_folder") ? (r.setAttribute("directory", ""), r.setAttribute("webkitdirectory", "")) : (r.removeAttribute("directory"), r.removeAttribute("webkitdirectory"));
                    break;
                case "multiple":
                    t && i.can("select_multiple") ? r.setAttribute("multiple", "") : r.removeAttribute("multiple")
            }
        },
        disable: function(e) {
            var t, i = this.getRuntime();
            (t = n.get(i.uid)) && (t.disabled = !!e)
        },
        destroy: function() {
            var

                t = this.getRuntime(),
                i = t.getShim(),
                o = t.getShimContainer(),
                a = e && n.get(e.container),
                u = e && n.get(e.browse_button);
            a && r.removeAllEvents(a, this.uid), u &&

                (r.removeAllEvents(u, this.uid), u.style.zIndex = s), o &&

                (r.removeAllEvents(o, this.uid), o.innerHTML = ""), i.removeInstance(this.uid), e = o = a = u = i = null
        }
    })
}
return e.FileInput = s
}), n("moxie/runtime/html5/file/FileDrop",

        ["moxie/runtime/html5/Runtime", "moxie/file/File", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Events", "moxie/core/utils/Mime"],
        function(e, t, i, n, r, o) {
            function a() {
                function e(e) {
                    if (!e.dataTransfer || !e.dataTransfer.types) return !1;
                    var

                        t = i.toArray(e.dataTransfer.types || []);
                    return -1 !== i.inArray("Files", t) || -1 !== i.inArray("public.file-url", t) || -1 !== i.inArray("application/x-moz-file", t)
                }

                function a(e, i) {
                    if (u(e)) {
                        var n = new

                        t(f, e);
                        n.relativePath = i || "", p.push(n)
                    }
                }

                function s(e) {
                    for (var t = [], n = 0; n < e.length; n++)[].push.apply(t, e[n].extensions.split(/\s*,\s*/));
                    return -1 === i.inArray("*", t) ? t : []
                }

                function u(e) {
                    if (!g.length) return !0;
                    var t = o.getFileExtension(e.name);
                    return !t || -1 !== i.inArray(t, g)
                }

                function c(e, t) {
                    var n = [];
                    i.each(e, function(e) {
                        var t = e.webkitGetAsEntry();

                        t && (t.isFile ? a(e.getAsFile(), t.fullPath) : n.push(t))
                    }), n.length ? l(n, t) : t()
                }

                function l(e, t) {
                    var n = [];
                    i.each(e, function(e) {
                        n.push(function(t) {
                            d(e, t)
                        })
                    }), i.inSeries(n, function() {
                        t()
                    })
                }

                function d(e, t)


                {
                    e.isFile ? e.file(function(i) {
                        a(i, e.fullPath), t()
                    }, function() {
                        t()
                    }) : e.isDirectory ? m(e, t) : t()
                }

                function m(e, t) {
                    function i(e) {
                        r.readEntries(function(t) {
                            t.length ? ([].push.apply(n, t), i(e)) : e()
                        }, e)
                    }
                    var n = [],
                        r = e.createReader();
                    i(function() {
                        l(n, t)
                    })
                }
                var h, f, p = [],
                    g = [];
                i.extend(this, {
                    init: function(t) {
                        var n, o = this;

                        h = t, f = o.ruid, g = s(h.accept), n = h.container, r.addEvent(n, "dragover", function(t) {
                            e(t) && (t.preventDefault(), t.dataTransfer.dropEffect = "copy")
                        }, o.uid), r.addEvent(n, "drop", function(t) {
                            e(t) && (t.preventDefault(), p = [], t.dataTransfer.items && t.dataTransfer.items[0].webkitGetAsEntry ? c(t.dataTransfer.items, function() {
                                o.files = p, o.trigger("drop")
                            }) : (i.each(t.dataTransfer.files, function(e) {
                                a(e)
                            }), o.files = p, o.trigger("drop")))
                        }, o.uid), r.addEvent(n, "dragenter", function() {
                            o.trigger("dragenter")
                        }, o.uid), r.addEvent(n, "dragleave", function() {
                            o.trigger("dragleave")
                        }, o.uid)
                    },
                    destroy: function() {
                        r.removeAllEvents(h && n.get(h.container), this.uid), f = p = g = h = null, this.getRuntime().getShim().removeInstance(this.uid)
                    }
                })
            }
            return e.FileDrop = a
        }), n("moxie/runtime/html5/file/FileReader", ["moxie/runtime/html5/Runtime", "moxie/core/utils/Encode", "moxie/core/utils/Basic"], function(e, t, i) {
            function n() {
                function e(e) {
                    return t.atob(e.substring(e.indexOf("base64,") + 7))
                }
                var n, r = !1;
                i.extend(this, {
                    read: function(t, o) {
                        var a = this;
                        a.result = "", n = new window.FileReader, n.addEventListener("progress", function(e) {
                                a.trigger(e)
                            }), n.addEventListener("load", function(t) {
                                a.result = r ? e(n.result) : n.result, a.trigger(t)
                            }), n.addEventListener("error", function(e) {
                                a.trigger(e, n.error)
                            }), n.addEventListener("loadend", function(e) {
                                n = null, a.trigger(e)
                            }), "function" === i.typeOf(n[t]) ? (r = !1, n[t](o.getSource())) : "readAsBinaryString" === t &&

                            (r = !0, n.readAsDataURL(o.getSource()))
                    },
                    abort: function() {
                        n && n.abort()
                    },
                    destroy: function() {
                        n = null, this.getRuntime().getShim().removeInstance(this.uid)
                    }
                })
            }
            return
7
  • el tema es que ahí file_upload es un anchor que llama a un javascript, habría que ver que hace el javascript (si abre un modal u otra cosa) y así localizar el input type="file" que es el que recibiría el sendkeys (el nombre/ruta del archivo a subir) el 8 jul. 2018 a las 18:51
  • Hola, gracias or contestar... acabo de buscar en el javaScript y es una locura... está codificado.. localicé el elemento pero el id es una varible... <input id="'+g.uid+'" type="file.... ¿Alguna ídea de que se puede hacer? el 8 jul. 2018 a las 19:11
  • voy a intentar poner el fragmento de código de JavaScript ahí arriba el 8 jul. 2018 a las 19:15
  • 1
    probaría también un wait luego del click en el A (para darle un tiempo al script) y de ahi intentar un uid = driver.execute_script("return g.uid"); o tal vez buscarlo por selector input[type="file"], tambien esperando unos milisegundos para que le de tiempo al render el 8 jul. 2018 a las 19:20
  • 1
    La segunda opción funcionó :-).... puse esto img_upload = driver.find_elements_by_xpath("//input[@type='file']") ** y después esto **img_upload[0].send_keys(path_out) ... Muchisimas Gracias @aloMalbarez, me acabas de salvar la vida... llevaba dos dias haciendo este código y tengo que subir al servidor casi 25000 imagenes... el 8 jul. 2018 a las 19:55

1 respuesta 1

1

Para mas referencia lo que hay ahí es un fileupload usando moxie.js un ejemplo de código no comprimido está en https://github.com/moxiecode/moxie/wiki/File-Picker

como te comentaba lo que generalmente funciona es enviarle el click al activador, esperar un poco y luego buscar el INPUT type="file" creado por la librería.

En caso de que sean varios creas una lista:

file_tag_list =driver.find_elements_by_xpath(//input[@type="file"])

y los accedes por índice

file_tag_list[0].send_keys(filepath)
file_tag_list[1].send_keys(filepath)

ref: https://stackoverflow.com/a/30397244/1423096

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.