我试图通过Windows中的GUI应用程序在Selenium脚本中打开Firefox浏览器。 运行python.exe runw.py
时工作得很好 ,但是当我用pythonw.exe runw.py
运行它时,浏览器无法启动。 相反,它引发了这个例外:
Traceback (most recent call last): File "bin\runw.py", line 215, in process_instance instance.setup() File "bin\mixin.py", line 181, in setup self.browser = self.get_firefox_browser() File "bin\mixin.py", line 166, in get_firefox_browser firefox_binary=binary, firefox_profile=profile) File "C:\myvirtualenv\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 59, in __init__ self.binary, timeout), File "C:\myvirtualenv\lib\site-packages\selenium\webdriver\firefox\extension_connection.py", line 47, in __init__ self.binary.launch_browser(self.profile) File "C:\myvirtualenv\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py", line 60, in launch_browser self._start_from_profile_path(self.profile.path) File "C:\myvirtualenv\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py", line 83, in _start_from_profile_path env=self._firefox_env).communicate() File "C:\Python27\Lib\subprocess.py", line 702, in __init__ errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr) File "C:\Python27\Lib\subprocess.py", line 833, in _get_handles p2cread = self._make_inheritable(p2cread) File "C:\Python27\Lib\subprocess.py", line 884, in _make_inheritable _subprocess.DUPLICATE_SAME_ACCESS) WindowsError: [Error 6] The handle is invalid
问题当然在于没有stdin
或stdout
(我不确定),因为它在这一行失败( firefox_binary.py
):
def _start_from_profile_path(self, path): ... Popen(command, stdout=self._log_file, stderr=STDOUT, env=self._firefox_env).communicate() command[1] = '-foreground' self.process = Popen( command, stdout=self._log_file, stderr=STDOUT, env=self._firefox_env)
我已经尝试在运行浏览器之前用输出文件覆盖syd.stdout
,但是它不起作用:
sys.stdout = sys.stderr = open('log.txt', 'a+')
我正在运行Python2.7和Selenium 2.40。 Selenium如何运行pythonw
?
像@falsetru说的那样, subprocess
进程正在尝试用户文件描述符0
。 只有当所有句柄都是有效的(或者全部为None
)时,子进程调用才会起作用。由于pythonw
是一个Windows进程,并且没有任何进程,所以我被强制FirefoxBinary
以使用nul
句柄:
class WindowsFirefoxBinary(FirefoxBinary): def _start_from_profile_path(self, path): self._firefox_env["XRE_PROFILE_PATH"] = path if platform.system().lower() == 'linux': self._modify_link_library_path() command = [self._start_cmd, "-silent"] if self.command_line is not None: for cli in self.command_line: command.append(cli) # Added stdin argument: nul = open(os.devnull, 'w+') Popen(command, stdin=nul, stdout=self._log_file or nul, stderr=STDOUT, env=self._firefox_env).communicate() command[1] = '-foreground' self.process = Popen( command, stdin=nul, stdout=self._log_file or nul, stderr=STDOUT, env=self._firefox_env)
这样,我可以在创建WebDriver实例时使用我自己的二进制文件:
binary = WindowsFirefoxBinary() browser = webdriver.Firefox(firefox_binary=binary)
这可能是一个错误,或者仅仅是seleniumium与Windows for Python的兼容性问题。
似乎subprocess
sys.stdin
尝试使用标准输入(文件描述符0
,而不是sys.stdin
)。
解决方法:在脚本的开始处打开一个文件以读取 (使文件描述符0 subprocess
代码使用)。
import os open(os.devnull, 'r')