Home > OS >  Using XPath to select button inside HTML with content of tag instead of numbered list
Using XPath to select button inside HTML with content of tag instead of numbered list

Time:02-12

Forum,

I am using python selenium to automate common behavior through a website. I have now arrived at a point where there is a div <div data-baan="1"> with a number of <div teetime-grid" data-baan="1"> <a href="#"> <div data-time="1645165200" title="Er zijn nog 3 beschikbare plaatsen op deze starttijd"> <span >07:20</span> <div > <span >&nbsp;</span> <span >&nbsp;</span> <span >&nbsp;</span> <span >&nbsp;</span> </div> </div> </a> <a href="#"> <div data-time="1645165800" title="Er zijn nog 1 beschikbare plaatsen op deze starttijd"> <span >07:30</span> <div > <span >&nbsp;</span> <span >&nbsp;</span> <span >&nbsp;</span> <span >&nbsp;</span> </div> </div> </a> </div>

I need to access specific <div //a[2]/div")

to select the second tag in my above example, which in this case has a corresponding time of 07:30 associated with it (it's defined in the <span >07:30</span>).

Is there also a way to access these elements by the contents of the <span >... instead of specifying the number in the list of <a href> tags? Because now I still have to know which a[?] number corresponds to a certain time. If I have to look this up manually every time time there is no point in automating this browser action to begin with.

CodePudding user response:

This will find the div, which contains a specific span child 1 level down.

//span[@class='time'][text()='07:30']/..

And if you'll add one more /.., you'll find the a (the div parent).

CodePudding user response:

To access the specific <div https://stackoverflow.com/a/48056120/7429447">locator strategies:

  • Selecting 07:20:

    element = driver.find_element(By.XPATH, "//a[./span[text()='07:20']]")
    
  • Selecting 07:30:

    element = driver.find_element(By.XPATH, "//a[./span[text()='07:30']]")
    
  • Note : You have to add the following imports :

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