Home > Blockchain >  Python - Selenium get Element by attribute and the full attribute value
Python - Selenium get Element by attribute and the full attribute value

Time:01-22

Hi how can I get an element by attribute and the attribute value in Python Selenium?

For example I have .

Now I want to get the element with the attribute class what ca.rries the classes "class1 class2 class3".

Is this possible?

If I use xpath, I always need to add the element type, input, option,... I try to avoid the element type since it varies sometimes.

CodePudding user response:

The CSS selectors would be formatted like this:

'[attribute]'

'[attribute="value"]'

For example, the selector for the input field on google.com would be:

'input[name="q"]'

CodePudding user response:

to answer this part

If I use xpath, I always need to add the element type, input, option,... I try to avoid the element type since it varies sometimes.

you can use //* and then attribute type and attribute value.

//*[@class='class1 class2 class3']

//* represent any or all nodes

CodePudding user response:

While constructing locators considering or you have to use the different attributes and the attribute-values to identify the WebElement uniquely within the DOM Tree.

The generic way is:

  • Using css_selector:

    button.classname[attributeA='attributeA_value'][attributeB='attributeB_value']
    
  • Using xpath and attributes:

    //button[@attributeA='attributeA_value'][@attributeB='attributeB_value']
    

As an example, for an element like:

<button type="button" aria-hidden="true"  data-notify="dismiss">Close</button>

You can identify the Close element using either of it's the attributes and the corresponding attribute-values using either of the Locator Strategies:

  • Using css_selector:

    button.close.alert.alert-close[data-notify='dismiss']
    classes-> ^   ^^    ^^^        data-notify ^^^^ attribute
    
  • Using xpath and attributes:

    //button[@class='close alert alert-close' and @data-notify='dismiss']
     class attributes  ^    ^^     ^^^             data-notify ^^^^ attribute
    
  • Using xpath and innerText:

    //button[text()='Close']
           innerText ^
    
  •  Tags:  
  • Related