【问题标题】:Selenium Python - Upload image when element seems to be hiddenSelenium Python - 当元素似乎被隐藏时上传图像
【发布时间】:2020-01-27 07:15:18
【问题描述】:

所以基本上我在使用 Selenium Python 上传一些照片时遇到问题 input 元素似乎隐藏在页面中,因此 .sendkeys 方法仍然遇到一些错误。

这是输入元素的html代码

 <div data-react-class="ImageUploadForm" data-react-props="{}" data-react-cache-id="ImageUploadForm-0">
  <input class="hidden" type="file" accept="image/jpeg, image/jpg, image/png, image/gif">
  <button class="btn btn-lemonfrog text-lg" type="button">Upload photo</button>
 </div>
base_path = Path(file).parent
filepath = (basepath / "../core/attachments/clientstackphoto.jpeg").resolve()
hiddenuploaderinput.sendkeys(filepath)

现在运行上面的代码后,我收到了类型错误: value = (PosixPath('........./core/attachments/clientstackphoto.jpeg'),)

def keys_to_typing(value):
    """Processes the values that will be typed in the element."""
    typing = []
    for val in value:
        if isinstance(val, Keys):
            typing.append(val)
        elif isinstance(val, int):
            val = str(val)
            for i in range(len(val)):
                typing.append(val[i])
        else:
          for i in range(len(val)):

E TypeError: 'PosixPath' 类型的对象没有 len()

../../venv/lib/python3.7/site-packages/selenium/webdriver/common/utils.py:150: TypeError

我希望上传照片成功,也许一些js注入会有所帮助?

【问题讨论】:

    标签: javascript python selenium image-uploading hidden-field


    【解决方案1】:

    根据您的错误消息,我不完全相信错误消息是由隐藏文件输入引起的。如果是的话,我会期待ElementNotVisibleException

    但是,我确实看到输入是隐藏的,所以我们应该运行一些 JS 来显示输入,也许我们可以将其排除为潜在问题。

    显示图像输入的代码

    fileInput = driver.find_element_by_xpath("//input[@type='file']")
    
    # display file input so we can send keys
    driver.execute_script("arguments[0].style.display = 'block';", fileInput)
    

    或者,您可能需要在 class 属性上执行脚本:

    driver.execute_script("arguments[0].setAttribute('class', 'visible')", fileInput)
    

    一旦你执行 JS 使文件输入可见,你可以像任何其他输入一样 send_keys 给它:

    fileInput.send_keys("PATH/TO/FILE/HERE")
    

    【讨论】:

    • 好像还有其他一些错误 regrading type error:in send_keys {'text': "".join(keys_to_typing(value)), E TypeError: object of type 'PosixPath' has no len() selenium/webdriver/common/utils.py:150: TypeError[100%]
    • 我会尝试复制相对路径到jpg文件
    • 除此之外,感谢 js 脚本,我肯定会有所帮助:)
    猜你喜欢
    • 2012-08-17
    • 2020-05-19
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多