Home > database >  Python - Selenium: How to find input element with a nested label inside as span tag via XPATH
Python - Selenium: How to find input element with a nested label inside as span tag via XPATH

Time:02-05

I am trying to find the input element inside a div tag with a sibling span with label containing text "Destination".

I am using Python with Selenium and looking for a XPATH expression. Tried various variations of XPATH expressions but could not find a solution.

<div >
    <input _ngcontent-luj-c437="" matinput="" type="text" formcontrolname="locationInput"  id="mat-input-2" aria-invalid="false" aria-required="false" autocomplete="off" role="combobox" aria-autocomplete="list" aria-expanded="true" aria-haspopup="true" aria-activedescendant="mat-option-286" aria-owns="mat-autocomplete-2">
    <!---->
    <mat-autocomplete _ngcontent-luj-c437="" autoactivefirstoption="" ><!----></mat-autocomplete>
    <mat-menu _ngcontent-luj-c437="" ><!----></mat-menu>
    <span >
        <label  id="mat-form-field-label-7" for="mat-input-2" aria-owns="mat-input-2">
            <!---->
            <mat-label _ngcontent-luj-c437="" >Destination</mat-label>
            <!---->
            <!---->
        </label>
        <!---->
    </span>
</div>

Thank you.

CodePudding user response:

Try to use something like this:

xpath_by_str = "//mat-label[text()='Destination']/ancestor::div[1]/input"

xpath_by_id = "//label[@id='mat-form-field-label-7']/ancestor::div[1]/input"

CodePudding user response:

The following XPATH expression can be used to select the input element with a nested label inside as a span tag in Selenium with Python

//div[./span/label/mat-label[text()='Destination']]/input
  • Related