在没有输入[type =“file =]元素的情况下上传selenium中的文件

问题描述 投票:0回答:1

我正在使用selenium和python,我正在尝试自动执行一项任务,要求我在Web应用程序中上传.csv文件。通常我会找到input [type = file]元素和send_keys(path_to_image)。

但在这种情况下,元素缺失。没有“浏览”按钮,只能拖放,只有.csv文件。

删除文件的框只是一个div,带有一些文本。虽然有2个输入元素,但它们的类型=“隐藏”且不可交互。

有一个脚本,我手动上传后可以看到数据。

它包含在一个名为MMContacts的var中。

var MMContacts = 
        {
            isDirty: false,
            isFeatureEnabled: true,
            isDisabled: false,
            data: [],

并且在定义了一些功能之后。以。。结束:

$(MMContacts.init);

我想知道是否有一种简单的方法来执行一些允许我填写MMContacts中的数据字段的Javascript,或者如果自动执行此操作的唯一方法是GUI Automation(我只知道JS的基础知识)

更新:整个脚本

MMToolbar.next = function()
{
    $("#mm-form input[name=dirty]").val(MMContacts.isDirty);

    if (MMContacts.isDirty)
    {
        var data = encodeURIComponent(JSON.stringify(MMContacts.data));
        data = btoa(data);
        $("#mm-form input[name=data]").val(data);
    }

    $("#mm-form").submit();
}

MMToolbar.prev = function()
{
    // window.history.back();
    window.location = "/mailmerge/settings?id=33053"
}

var MMContacts = 
{
    isDirty: false,
    isFeatureEnabled: true,
    isDisabled: false,
    data: [],

    init: function()
    {
        // arrange
        MMContacts.uploader = $("#uploader");
        MMContacts.grid = $("#grid");
        MMContacts.stats = $("#stats");
        MMContacts.dropzone = $("#uploader,#grid");

        // prepare dropzone
        MMContacts.dropzone.on("dragover", function(e) { e.preventDefault(); e.stopPropagation(); });
        MMContacts.dropzone.on("dragenter", function(e) { e.preventDefault(); e.stopPropagation(); });
        MMContacts.dropzone.on("drop", MMContacts.dropped);

        // refresh
        MMContacts.render();
    },

    render: function()
    {
        if (MMContacts.data.length == 0)
        {
            MMContacts.uploader.show();
            MMContacts.grid.hide();
            MMContacts.stats.html("");
        }
        else
        {
            MMContacts.uploader.hide();
            MMContacts.grid.show();
            MMContacts.refreshGrid();
            MMContacts.stats.html("Loaded " + MMContacts.data.length + " records - drop new file to replace.");
        }
    },

    dropped: function(e)
    {
        if (MMContacts.isDisabled)
            return;

        if (!e.originalEvent.dataTransfer)
            return;

        if (!e.originalEvent.dataTransfer.files.length)
            return;

        e.preventDefault();
        e.stopPropagation();

        var file = e.originalEvent.dataTransfer.files[0];

        // make sure file format is correct
        /*if (file.type != "text/csv")
        {
            var type = (file.type.indexOf("spreadsheet") > -1) ? "XLSX" : file.type;
            alert("Contact list must be a (CSV) file.\n\nThe file you are uploading is of type (" + type + "). Please open the file in a spreadsheet software (Excel or Google Spreadsheet) and save it as a CSV file.");
            return;
        }*/

        if (!file.name.endsWith(".csv"))
        {
            var type = (file.type.indexOf("spreadsheet") > -1) ? "XLSX" : file.type;
            alert("Contact list must be a (CSV) file.\n\nThe file you are uploading is of type (" + type + "). Please open the file in a spreadsheet software (Excel or Google Spreadsheet) and save it as a CSV file.");
            return;
        }

        // clean/trim file before processing
        var reader = new FileReader();

        reader.onloadend = function(event) {
            var lines = event.target.result.trim().split("\n");
            var data = [];

            for(var i = 0; i < lines.length; i++)
            {
                var line = lines[i];

                // skip if empty line
                if (line.trim().length == 0) continue;

                // skip if only commas
                var clean = line.replace(/\s+/g, "");
                if (clean.length == clean.split(",").length -1) continue;

                data.push(line);
            }

            MMContacts.parseContent(data.join("\n"));
        }

        reader.readAsText(file);
    },

    parseContent: function(data)
    {
        Papa.parse(data, {
            header: true,
            complete: function(results) {

                // validate file is not empty
                if (results.data.length < 0)
                {
                    Modal.alert("The file you chose is empty.");
                    return;
                }

                // restrict non-premium users
                if (!MMContacts.isFeatureEnabled && results.data.length > 20)
                {
                    $("#premium-notice").show();
                    return;
                }
                else
                {
                    $("#premium-notice").hide();
                }

                // validate it's not too large
                if (results.data.length > 200)
                {
                    $("#limit-notice #limit-uploaded").html(results.data.length);
                    $("#limit-notice").show();
                    return;
                }
                else
                {
                    $("#limit-notice").hide();
                }

                // confirm email is a field
                var header = Object.keys(results.data[0]).map(i => i.toLowerCase() );

                if (header.indexOf("email") == -1)
                {
                    var bracketedHeaders = Object.keys(results.data[0]).map(i => "["+i+"]" );
                    alert("Your CSV doesn't contain an email column. Make sure the name of the column is 'email', lower case, without dashes or extra spaces.\n\nColumns found (check for spaces):\n" + bracketedHeaders.join("\n"));
                    return;
                }

                // all good? set data
                MMContacts.isDirty = true;
                MMContacts.data = results.data;
                MMContacts.render();
            }
        });
    },

    refreshGrid: function()
    {
        // make fields
        var fields = Object.keys(MMContacts.data[0]).map(function(i) {
            return { name: i, type: "text" };
        });

        // add row # field
        fields.unshift({name: "#", type: "text", css: "row-col"});

        var index = 1;
        var clone = JSON.parse(JSON.stringify(MMContacts.data));

        clone.map(function(i) {
            i["#"] = index++;
            return i;
        });

        // show grid
        MMContacts.grid.jsGrid({
            height: "250px",
            width: "100%",
            data: clone,
            fields: fields
        });
    }
}

$(MMContacts.init);

html中的表单部分:

<form id="mm-form" method="post">
        <h2>Contacts</h2>
        <span>Populate your target contacts</span>

        <div id="limit-notice">
            A single mail merge campaign is limited to 200 contacts (<a href="https://vocus.io/mailmerge-limit" target="_blank">learn why</a>). 
            The contact list you are trying to upload includes <span id="limit-uploaded"></span> contacts. 
            Consider splitting your contacts into multiple campaigns on different days to avoid the Gmail-imposed daily limit. 
        </div>

        <div id="premium-notice">
            Your plan is limited to 20 contacts per campaign, and no more than three campaigns. Please upgrade to the Starter or Professional Plan. See Dashboard &gt; Billing.
        </div>


        <div id="uploader">
            drop CSV here<br>
            make sure it has an "email" column
        </div>

        <div id="grid" style="display: none;"></div>
        <div id="stats"></div>

        <input type="hidden" name="dirty" value="false">
        <input type="hidden" name="data" value="">

    </form>
python-3.x file selenium automation
1个回答
0
投票

我以前遇到过这个问题,并且能够使用WebDriver的javascript执行器取消隐藏输入。这是我在Java中的表现,python代码应该非常相似。

evaluateJavascript("document.getElementById('upload').style['opacity'] = 1");
upload(jobseeker.cv()).to(find(By.cssSelector("#upload")));
© www.soinside.com 2019 - 2024. All rights reserved.