Django Selenium点击ajax模态弹出窗口

时间:2018-04-19 21:42:22

标签: python django selenium selenium-webdriver modal-dialog

我目前正在为我的大学做一些任务。我为我的应用程序编写了Django Selenium测试。我试图编写删除对象的测​​试。

我的代码的关键部分是:

删除confirmation.html

<form action="" method="post" id="confirmForm">{% csrf_token %}
    <p>{% trans "Are you sure you want to delete this car?" %}</p>
    <input class="center-block btn btn-danger" type="submit" value="{% trans 'Confirm' %}"/>
</form>

modal.js

function showModal(url) {
    $("#myModalBody").text();
    $("#myModal").modal();
    $.ajax({
        url,
        cache: false
    }).done(function (html) {
        $("#myModalBody").html(html);
        $("#confirmForm").attr('action', url);
    });

}

点击以下按钮时

<button class="btn btn-primary btn-sm pull-left" value="" id="car-delete-modal-btn m-10-b" onclick="showModal('{% url 'c2crental:delete_car' details_car.id %}');">{% trans "Delete car" %}</button>

Modal appears

测试因结果而停止:无法找到元素。我试图使用不同的选择器,但没有一个工作。现在测试看起来像这样:

# click 'delete' button to display popup confirmation window
delete_btn = self.selenium.find_element_by_id('car-delete-modal-btn m-10-b')
delete_btn.click()

# click 'confirm' to delete object in popup window
submit = 'input[type="submit"]'
confirm_btn = self.selenium.find_element_by_id(submit)
confirm_btn.click()

我似乎无法为此按钮找到合适的选择器,或者它是同步问题。有人可以帮我解决吗?

很抱歉我的英语很糟糕,我希望你能理解我在这里要做的事情,但我只是从Django开始,测试,编程一般,所以不是一切都很清楚。

2 个答案:

答案 0 :(得分:1)

These lines are causing your problem:

submit = 'input[type="submit"]'
confirm_btn = self.selenium.find_element_by_id(submit)

You are trying to pass CSS to an id selector.

I would try adding this before trying to click on the submit:

# Make sure to import these first
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(self.selenium, 10).until(EC.element_to_be_clickable((By.XPATH, './/*[@id="confirmForm"]//input[@type="submit"]'))

Then try this click instead of id, XPATH:

self.selenium.find_element_by_xpath('.//*[@id="confirmForm"]//input[@type="submit"]').click()

答案 1 :(得分:1)

@PixelEinstein的答案是正确的方向,但我认为 WebDriverWait 超时,因为节点input[@type="submit"]不是{的直接子节点{1}}。

也许,您可以使用以下定位器策略来诱导 WebDriverWait

[@id="confirmForm"]