pythonselenium-webdriver

Why Selenium webdriver is not Imported


>>> import selenium
>>> selenium.webdriver
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'selenium' has no attribute 'webdriver'
>>> from selenium import *
>>> webdriver
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'webdriver' is not defined
>>> from selenium import webdriver
>>> webdriver
<module 'selenium.webdriver' from 'C:\\Python312\\Lib\\site-packages\\selenium\\webdriver\\__init__.py'>

In this code why selenium doesn't import webdriver unless if asked explicitly. According to my current understanding, if not asked, in python all classes/functions should load. then why webdriverd was not imported when we import all classes/functions from module unless asked explicitly.

I was expecting webdriver to be load when i load selenium module or all classes/functions from selenium module but webdriver wasn't imported and is only loaded when asked explicitly.

Edit: To add more context, I am using Windows OS. Also, I don't have a file named selenium.py in the current directory, which could conflict with the selenium module.


Solution

  • According to my current understanding, if not asked, in python all classes/functions should load.

    The flaw in your understanding is that selenium.webdriver is not a class or function. In reality, selenium.webdriver is a module, and it has to be imported, rather than used as if it was an object.

    Note that importing the selenium module doesn't import its child modules; i.e. webdriver, webdriver.common and so on. If you thought that it would or should do that, your understanding is incorrect.

    Try getting started with Selenium by copying the "simple usage" example provided in https://selenium-python.readthedocs.io/getting-started.html#simple-usage:

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    
    driver = webdriver.Firefox()
    driver.get("http://www.python.org")
    assert "Python" in driver.title
    elem = driver.find_element(By.NAME, "q")
    elem.clear()
    elem.send_keys("pycon")
    elem.send_keys(Keys.RETURN)
    assert "No results found." not in driver.page_source
    driver.close()
    

    It seems to me that you need to do some more work on your understanding of Python modules, how they work, and how you use them.