如何在python中的硒中添加文件属性到webelement

How to add files property to webelement in selenium in python

本文关键字:添加 文件属性 webelement python      更新时间:2023-09-26

我有硒网元素:
input_elem = driver.find_element_by_class_name("inline_upload")
我想将文件添加到其中。然后在执行js脚本时使用它
driver.execute_script("func(input_elem);")
func 使用此文件的位置:

func: function(e) {
    a = e.files[0]
    b = attr(e, "some_attr)
}

所以我必须将文件属性添加到我的硒 webelement 中,然后用文件(二进制?)初始化此属性,或者用硒初始化新的输入文件上传对象。

我该怎么做?

此示例注入事件侦听器以允许与上传的文件进行交互:

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://fiddle.jshell.net/lovlka/N4Jxk/show/")
driver.switch_to_frame(0)
# find the input
input_elem = driver.find_element_by_css_selector("#uploadFile")
# add an event listener on the input element
driver.execute_script("""'
  arguments[0].addEventListener("change", function onchange() {
    this.removeEventListener("change", onchange);
    var files = this.files;
    alert('a file was uploaded');
  });
  """, input_elem)
# upload the file
input_elem.send_keys(r"C:'text.txt")