Selenium 无法从目录中找到文件'/tmp/'以填充文件输入



我想使用selenium Firefox驱动程序上传一个文件。这个文件是动态生成的,不需要持久保存,所以我想把它放在/tmp/下。

当从我的home目录中选择文件时,工作得很好:

from selenium import webdriver
from pathlib import Path
driver = webdriver.Firefox()
driver.get("https://viljamis.com/filetest/")
Path(f"{Path.home()}/my_test_file").touch()
driver.find_element('xpath', '//input[@type="file"]').send_keys(f"{Path.home()}/my_test_file")

对位于/tmp/my_test_file的文件做同样的操作,如下所示:

from selenium import webdriver
from pathlib import Path
driver = webdriver.Firefox()
driver.get("https://viljamis.com/filetest/")
Path(f"/tmp/my_test_file").touch()
driver.find_element('xpath', '//input[@type="file"]').send_keys(f"/tmp/my_test_file")

将导致以下粗略的错误消息:

Traceback (most recent call last):
File "/home/username/Downloads/test.py", line 12, in <module>
driver.find_element('xpath', '//input[@type="file"]').send_keys(f"/tmp/my_test_file")
File "/home/username/.local/lib/python3.10/site-packages/selenium/webdriver/remote/webelement.py", line 233, in send_keys
self._execute(
File "/home/username/.local/lib/python3.10/site-packages/selenium/webdriver/remote/webelement.py", line 410, in _execute
return self._parent.execute(command, params)
File "/home/username/.local/lib/python3.10/site-packages/selenium/webdriver/remote/webdriver.py", line 444, in execute
self.error_handler.check_response(response)
File "/home/username/.local/lib/python3.10/site-packages/selenium/webdriver/remote/errorhandler.py", line 249, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidArgumentException: Message: File not found: /tmp/my_test_file
Stacktrace:
RemoteError@chrome://remote/content/shared/RemoteError.sys.mjs:8:8
WebDriverError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:182:5
InvalidArgumentError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:311:5
interaction.uploadFiles@chrome://remote/content/marionette/interaction.sys.mjs:537:13

很奇怪,因为文件确实存在

我找不到让它工作的方法。为什么从/tmp/中选择文件会有差异?

访问权限是两次-rw-rw-r--和通过点击"browse…"手动选择文件。按钮和选择文件也可以很好地工作。

编辑:我正在运行一个相当新的Kubuntu 22.04.1

在Ubuntu 22.04上遇到同样的问题,以.deb(不是Snap)的形式安装firefox帮助了我。

  1. 删除Firefox Snap:

sudo snap remove firefox

  1. 将(Ubuntu) Mozilla团队PPA添加到您的软件源代码列表:

sudo add-apt-repository ppa:mozillateam/ppa

  1. 更改Firefox包优先级:

echo ' Package: * Pin: release o=LP-PPA-mozillateam Pin-Priority: 1001 ' | sudo tee /etc/apt/preferences.d/mozilla-firefox

  1. 设置firefox自动更新:

echo 'Unattended-Upgrade::Allowed-Origins:: "LP-PPA-mozillateam:${distro_codename}";' | sudo tee /etc/apt/apt.conf.d/51unattended-upgrades-firefox

  1. 通过apt安装Firefox

sudo apt install firefox

使用如下说明:https://www.omgubuntu.co.uk/2022/04/how-to-install-firefox-deb-apt-ubuntu-22-04

相关内容

最新更新