OSError: [WinError 193] %1 is not a valid Win32 application error using GeckoDriver and Firefox through Selenium and Python on Windows

OSError: [WinError 193] %1 is not a valid Win32 application error using GeckoDriver and Firefox through Selenium and Python on Windows

我在 Ubuntu 中使用 selenium 创建了脚本并且在那里工作得很好,但是当我将它移动到 windows10 时,我遇到了很多错误,我试图一个一个地修复它直到我看到这个错误。我一直在寻找这个问题的解决方案,但我无法解决这个错误。

Traceback (most recent call last):
  File "D:/Users/b/Documents/Python/Bolt/GUI.py", line 180, in start
    driver = l.start_chime()  # start chime
  File "D:\Users\b\Documents\Python\Bolt\Login.py", line 87, in start_chime
    self.chime_driver = webdriver.Firefox(executable_path=self.PATH)
  File "D:\Users\b\Documents\Python\Python3.8\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 164, in __init__
    self.service.start()
  File "D:\Users\b\Documents\Python\Python3.8\lib\site-packages\selenium\webdriver\common\service.py", line 72, in start
    self.process = subprocess.Popen(cmd, env=self.env,
  File "D:\Users\b\Documents\Python\Python3.8\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "D:\Users\b\Documents\Python\Python3.8\lib\subprocess.py", line 1307, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
  File "C:\Program Files\JetBrains\PyCharm 2020.1.2\plugins\python\helpers\pydev\_pydev_bundle\pydev_monkey.py", line 551, in new_CreateProcess
    return getattr(_subprocess, original_name)(app_name, patch_arg_str_win(cmd_line), *args)
OSError: [WinError 193] %1 is not a valid Win32 application

这是在我尝试使用 selenium 打开 webdriver 时发生的。

self.myday_driver = webdriver.Firefox(executable_path=self.PATH)

有什么方法可以将脚本从 Ubunto 移动到 Windows 而不会出错?

我会尽量帮你回答最后一个问题:

and is there any method to move script from Ubunto to Windows without getting error?

是的,你听说过docker吗? https://www.docker.com/ 本质上,docker 将创建 隔离环境 ,这将 运行 在每台安装了 docker 的机器中。这些环境可在 docker 文件中配置,基本上,您需要按照以下步骤操作:

  • 在两台机器上安装 docker。我已经在 Windows 和 RH 上使用来自动执行所有这些过程并最大限度地减少错误。
  • 创建一个docker file,结构类似于:
FROM ubuntu:18.04
COPY . /app
RUN make /app
CMD python /app/app.py
  • 因此它将创建一个基于 ubuntu image
  • 的环境
  • 将当前目录 (.) 中的所有文件复制到 /app(记住这将是一个 ubuntu 图像,因此您有一个标准的文件夹结构,包括 /etc /home 等)
  • 运行 命令 make(在你的情况下可以使用 pip 安装一些依赖项)
  • 运行 python 命令。

您还可以找到可供使用的 python 图像,因此您可以获得安装了 python 的图像 linux 而不是 ubuntu:latest,然后您只需安装您的依赖项。

这对开​​发人员来说是一个很好的工具,我建议研究它,阅读文档以理解概念,这会让您的生活变得轻松。

希望对您有所帮助。

这个错误信息...

OSError: [WinError 193] %1 is not a valid Win32 application

...意味着底层 OS 无法识别 %1 即系统变量 PATH 作为有效的 Win32 应用程序即 可执行二进制文件.


要启动一个 driven 控制的 Firefox 会话,您需要:

  • 下载最新版本的GeckoDriver二进制版本,将其放入您的系统中。

  • 接下来,在您的代码块中,您需要通过 Key [=] 提及 binary 的绝对路径 executable_path如下:

    from selenium import webdriver
    
    self.myday_driver = webdriver.Firefox(executable_path=r'C:\path\to\geckodriver.exe')