在表单selenium + python中提交按钮

时间:2018-05-15 09:03:58

标签: django python-3.x selenium

我有这个表单,其中包含一个具有一些动态值的按钮,当我点击它时,它应该将产品添加到结帐页面。 这是html表单:

    {%for p in product %}
 <div class="single-product">
    <div class="product-f-image">
      <img src="data:image/png;base64,{{p.image_medium}}" alt="">
         <div class="">
       {% if not user.is_authenticated %}
      <form action="/login/">
       <button class="add-to-cart-link" type="submit"> Add to cart</button>
      </form>
      {%else%}
    <form id="form-id"  action="" method="POST">
    {% csrf_token %}
  <button class="add-to-cart-link" type="submit" name="product" value="{{p.id}}" >
<input type="hidden" name="product_name" value="{{p.name}}">
<input type="hidden" name="product_price" value="{{p.lst_price}}">
    Add to cart</button>
  </form>
     {%endif%}
 <a href="#" class="view-details-link"><i class="fa fa-link"></i> See details</a>
 </div>
  </div>
 <h2><a href="single-product.html">{{p.id}}</a></h2>
<div class="product-carousel-price">
 <ins>{{p.lst_price}} €</ins>
                                </div>

                            </div>
                            {%endfor%}

以下是我用硒做的事情:

bon_commande = self.selenium.find_element_by_xpath("//button[@name='product' and @value='37']/parent::form")
bon_commande.submit()

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

您无需找到提交按钮即可提交表单 - 在表单或form元素本身中使用任何元素:

self.selenium.find_element_by_id("form-id").submit()

self.selenium.find_element_by_class_name("add-to-cart-link").submit()

更新

尝试等到django变量"{{p.id}}"替换为生成的值:

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.presence_of_element_located((By.XPATH, "//button[@name='product' and @value='37']"))).submit()

答案 1 :(得分:0)

更改为单击提交按钮:

// add some sleep to wait the JS files of page 
// load completely to register click event to the submit button
// otherwise nothing to response to the click 
// (because the `action` of the form is empty.)

self.selenium.sleep(15); // sleep 15 seconds
self.selenium.find_element_by_xpath("//button[@name='product' and @value='37']").click()

答案 2 :(得分:0)

要点击带有添加到购物车文字的按钮,您可以使用以下代码行:

self.selenium.find_element_by_xpath("//form[@id='form-id']/button[@class='add-to-cart-link' and @name='product']").submit()
#or
self.selenium.find_element_by_xpath("//form[@id='form-id']/button[@class='add-to-cart-link' and @name='product']").click()