Home > OS >  Selenium By.XPATH - what to import?
Selenium By.XPATH - what to import?

Time:07-21

New Selenium has no old metods like .find_element_by_xpath() but it introduced new fabrique method .find_element(By.XPATH, searched_string). Here is the example from docs:

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

But it does not work, bc '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 to do in Python?

CodePudding user response:

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")
    

CodePudding user response:

You have to import the class By

from selenium.webdriver.common.by import By

CodePudding user response:

from selenium.webdriver.common.by import By 
  • Related