上传文件 - 使输入可见(错误:ElementNotVisibleException)

时间:2016-01-13 23:07:56

标签: python selenium file-upload selenium-webdriver automated-tests

目前我有这个输入

<label class="bold grey-rectangle" data-uploading="Uploading" data-completed="Upload completed">
  <span>+ Add certificate</span>
  <input type="file" data-validation-allowing="jpg, jpeg, pdf" data-validation="mime" name="qualification2">
  <div class="spinner hidden">
  <div class="spinner-inner"></div>
  </div>
</label>

我想发送一个文件,所以我运行以下代码:

self.driver.execute_script("document.getElementsByName('qualification2')[0].style.display='block';")
self.driver.find_element_by_name("qualification2").send_keys("certificate.jpeg")

但我收到以下错误

ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with

如何有效地使用python和selenium进行上传?

1 个答案:

答案 0 :(得分:2)

您应该尝试删除hide以使元素可见:

elm = self.driver.find_element_by_name("qualification2")
self.driver.execute_script('arguments[0].removeAttribute("class");', elm)

elm.send_keys("/absolute/path/to/certificate.jpeg")

使用您提供的链接进行测试:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://your/site")

elm = driver.find_element_by_name("qualification2")
driver.execute_script('arguments[0].removeAttribute("class");', elm)

elm.send_keys("/Users/user/Downloads/test.jpg")

制作人:

enter image description here

请注意,在Firefox中,您还必须将margin-left样式属性重置为0才能使元素真正可见:

driver.execute_script('arguments[0].removeAttribute("class"); arguments[0].style["margin-left"] = 0;', elm)