1

The new version of Selenium doesn’t have any old methods, like .find_element_by_xpath(), but it introduced the new fabrique method .find_element(By.XPATH, searched_string). Here is the example from the documentation:

vegetable = driver.find_element(By.CLASS_NAME, "tomatoes")

But it does not work, because 'By' is not defined. I can't find the example what to import to use this pattern. In Java it is:

import org.openqa.selenium.By;

And what should I do in Python?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vasyl Kolomiets
  • 365
  • 8
  • 20
  • At "compile" time ([Pylint](https://en.wikipedia.org/wiki/Pylint)), the error message may be *"`E0602: Undefined variable 'By' (undefined-variable)`"*. – Peter Mortensen Nov 10 '22 at 18:45
  • Re *"fabrique method"*: Do you mean *[factory method](https://en.wikipedia.org/wiki/Factory_method_pattern)*? – Peter Mortensen Nov 10 '22 at 18:50
  • The canonical question is *[Python Selenium Webdriver (name 'by' not defined)](https://stackoverflow.com/questions/44629970/python-selenium-webdriver-name-by-not-defined)*. – Peter Mortensen Nov 10 '22 at 19:18
  • Related (same underlying import problem, despite the title): *[How to get element by tag name or id in Python and Selenium](https://stackoverflow.com/questions/72342517/how-to-get-element-by-tag-name-or-id-in-python-and-selenium)* – Peter Mortensen Nov 10 '22 at 19:20

3 Answers3

4

You have to import the class By

from selenium.webdriver.common.by import By
Md. Fazlul Hoque
  • 15,806
  • 5
  • 12
  • 32
1
from selenium.webdriver.common.by import By 
vitaliis
  • 4,082
  • 5
  • 18
  • 40
0

selenium.webdriver.common.by

As per the documentation of the By implementation:

class By(object):
    """
    Set of supported locator strategies.
    """

    ID = "id"
    XPATH = "xpath"
    LINK_TEXT = "link text"
    PARTIAL_LINK_TEXT = "partial link text"
    NAME = "name"
    TAG_NAME = "tag name"
    CLASS_NAME = "class name"
    CSS_SELECTOR = "css selector"

So when you use By you have to import:

from selenium.webdriver.common.by import By

Usage

  • For CLASS_NAME:

    vegetable = driver.find_element(By.CLASS_NAME, "tomatoes")
    
  • For XPATH:

    vegetable = driver.find_element(By.XPATH, "//element_xpath")
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352