pythonseleniumselenium-webdriverselenium3selenium4

Locate an element using selenium xpath


I am trying to locate an element that has the following line in the chrome inspect code, <href="app/arp/home/profile">.

My line is:

driver.find_element(By.xpath("//a[@href='/app/arp/home/profile']")).click()

But I get the following error:

AttributeError: type object 'By' has no attribute 'xpath'

What is wrong?


Solution

  • Till Selenium v3.141.0 to locate an element using you can use the following syntax:

    driver.find_element_by_xpath("//a[@href='/app/arp/home/profile']")
    

    However, in the upcoming releases find_element_by_* commands will be deprecated

    def find_element_by_xpath(self, xpath):
        """
        Finds an element by xpath.
    
        :Args:
         - xpath - The xpath locator of the element to find.
    
        :Returns:
         - WebElement - the element if it was found
    
        :Raises:
         - NoSuchElementException - if the element wasn't found
    
        :Usage:
            ::
    
                element = driver.find_element_by_xpath('//div/td[1]')
        """
        warnings.warn("find_element_by_* commands are deprecated. Please use find_element() instead")
        return self.find_element(by=By.XPATH, value=xpath)
            
    

    From Selenium v4.x onwards the effective syntax will be:

    driver.find_element(By.XPATH, "//a[@href='/app/arp/home/profile']")
    

    An example: