0

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

For example I have class="class1 class2 class3".

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.

cruisepandey
  • 28,520
  • 6
  • 20
  • 38
FunHelp
  • 11
  • 2

3 Answers3

1

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" class="close alert alert-close" 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 ^
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

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"]'

Michael Mintz
  • 9,007
  • 6
  • 31
  • 48
  • thx. This means I can get the element like this: [class="class1 class2 class3"] However I still need to define an element type like input, div, textarea,... Is there an option where I do not need to add an element type? This would be helpful since I have various element types. – FunHelp Jan 21 '22 at 16:31
  • Both ``'input[name="q"]'`` and ``'[name="q"]'`` would be valid selectors. – Michael Mintz Jan 21 '22 at 16:33
0

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

cruisepandey
  • 28,520
  • 6
  • 20
  • 38