简体   繁体   English

Python Selenium 没有找到 chromedriver

[英]Python Selenium doesn't find chromedriver

I am trying to learn web scraping with Python and Selenium.我正在尝试使用 Python 和 Selenium 学习 web 刮擦。 However, I have been getting an error of FileNotFoundError: [Errno 2] No such file or directory: 'chromedriver' and I am 100% sure that the file is located on the path that I specified as I tried it with much simpler approach before and everything was working fine.但是,我收到FileNotFoundError: [Errno 2] No such file or directory: 'chromedriver' ,我 100% 确定该文件位于我指定的路径上,因为我之前用更简单的方法尝试过它一切正常。

This is my code right now;这是我现在的代码;

class Booking(webdriver.Chrome):
    def __init__(self, driver_path=r"/Users/username/Desktop/SeleniumDriver/chromedriver"):
        self.driver_path = driver_path
        os.environ["PATH"] += r"/Users/username/Desktop/SeleniumDriver"
        super(Booking, self).__init__()

    def land_first_page(self):
        self.get("https://website.com")


inst = Booking()
inst.land_first_page()

I have tried different many paths with/without r as prefix as well as /chromedriver with exe as an extension or without.我尝试了不同的许多路径,有/没有 r 作为前缀以及 /chromedriver 有 exe 作为扩展名或没有。 Nothing seems to be working.似乎没有任何工作。 I am getting the error that I mentioned above when instantiating the Booking class我在实例化 Booking class 时收到上面提到的错误

Instead of using OOP if I use the webdriver like this;如果我像这样使用 webdriver,而不是使用 OOP;

os.environ["PATH"] += r"/Users/username/Desktop/SeleniumDriver"

driver = webdriver.Chrome("/Users/username/Desktop/SeleniumDriver/chromedriver")
driver.get("https://website.com")

It works, and doesn't give me any errors, but I would prefer to use OOP approach as it much more clear for me to work with, especially when creating bots它有效,并且没有给我任何错误,但我更喜欢使用 OOP 方法,因为它对我来说更清楚,尤其是在创建机器人时

you must understand about relative and absolute file paths.您必须了解相对和绝对文件路径。 This will help you to open your chrome-driver.这将帮助您打开 chrome 驱动程序。 Check out this link hope it will help: Absolute path & Relative Path .查看此链接希望它会有所帮助: 绝对路径和相对路径

If you're using Mac/Linux, The location is okay如果您使用的是 Mac/Linux,位置还可以

/Users/username/Desktop/SeleniumDriver/chromedriver

If you're using Windows, you may need to specify from the actual drive如果您使用的是 Windows,您可能需要从实际驱动器中指定

C:/Users/username/Desktop/SeleniumDriver/chromedriver

You can try this hack by modifying this line您可以通过修改此行来尝试此 hack

super(Booking, self).__init__()

to this对此

super(Booking, self).__init__(driver_path)

Looking at the source code for the __init__ method there is no instance variables initialised there.查看__init__方法的源代码,那里没有初始化实例变量。 By that I mean for example there is nothing like self.driver_path = "path" .我的意思是,例如,没有什么像self.driver_path = "path"

def __init__(self, executable_path="chromedriver", port=0,
                 options=None, service_args=None,
                 desired_capabilities=None, service_log_path=None,
                 chrome_options=None, keep_alive=True):
        """
        Creates a new instance of the chrome driver.

        Starts the service and then creates new instance of chrome driver.

        :Args:
         - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
         - port - port you would like the service to run, if left as 0, a free port will be found.
         - options - this takes an instance of ChromeOptions
         - service_args - List of args to pass to the driver service
         - desired_capabilities - Dictionary object with non-browser specific
           capabilities only, such as "proxy" or "loggingPref".
         - service_log_path - Where to log information from the driver.
         - chrome_options - Deprecated argument for options
         - keep_alive - Whether to configure ChromeRemoteConnection to use HTTP keep-alive.
        """
        if chrome_options:
            warnings.warn('use options instead of chrome_options',
                          DeprecationWarning, stacklevel=2)
            options = chrome_options

        if options is None:
            # desired_capabilities stays as passed in
            if desired_capabilities is None:
                desired_capabilities = self.create_options().to_capabilities()
        else:
            if desired_capabilities is None:
                desired_capabilities = options.to_capabilities()
            else:
                desired_capabilities.update(options.to_capabilities())


        self.service = Service(
            executable_path,
            port=port,
            service_args=service_args,
            log_path=service_log_path)
        self.service.start()

        try:
            RemoteWebDriver.__init__(
                self,
                command_executor=ChromeRemoteConnection(
                    remote_server_addr=self.service.service_url,
                    keep_alive=keep_alive),
                desired_capabilities=desired_capabilities)
        except Exception:
            self.quit()
            raise
        self._is_remote = False

    def launch_app(self, id):
        """Launches Chrome app specified by id."""
        return self.execute("launchApp", {'id': id})

    def get_network_conditions(self):
        """
        Gets Chrome network emulation settings.

        :Returns:
            A dict. For example:

            {'latency': 4, 'download_throughput': 2, 'upload_throughput': 2,
            'offline': False}

        """
        return self.execute("getNetworkConditions")['value']

So in your code the line self.driver_path = driver_path is not doing anything.因此,在您的代码中, self.driver_path = driver_path行没有做任何事情。 It sets an instance variable that is not used by the parent class.它设置了一个不被父 class 使用的实例变量。

You can pass the path in the super statement to make it work:您可以在 super 语句中传递路径以使其工作:

super().__init__(executable_path = "/Users/username/Desktop/SeleniumDriver/chromedriver")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM