There is error “Invalid locator values passed in” in case we use find_element instead of find_element_by

前端 未结 2 1385
花落未央
花落未央 2020-12-11 23:49

I\'m using Python-Webdriver to automate a \"click\" action. Here is my code:

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


        
2条回答
  •  难免孤独
    2020-12-12 00:40

    According to the api doc private method find_elements and find_element takes two parameters each and you are passing one which is obviously wrong.

    And,

    myDynamicElement = driver.find_element(NEWS_OPTION)

    and

    myDynamicElement = driver.find_element_by_id('blq-nav-news')

    are NOT same. driver.find_element_by_id takes one parameter and thus this work and find_element takes two so that fails.

    So, literally you should be using

    myDynamicElement = driver.find_element(By.ID,'blq-nav-news')
    

    EDIT

    NEWS_OPTION = (By.ID, 'blq-nav-news') will return you ('id', 'blq-nav-news') whereas find_element() expects the first parameter to be the implementation of By class mechanism to locate the element not simply a string.

    A direct call of NEWS_OPTION = (By.ID, 'blq-nav-news') has returned me a tuple and the attribute of By.ID which is 'id' A simple print out of NEWS_OPTION = (By.ID, 'blq-nav-news') provided me

    ('id', 'blq-nav-news')

    And, here is the source of By class

    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"
    
        @classmethod
        def is_valid(cls, by):
            for attr in dir(cls):
                if by == getattr(cls, attr):
                    return True
            return False
    

提交回复
热议问题