Search code examples
pythonselenium-webdriverxpathcss-selectorswebdriver

Finding a specific span element with a class using Selenium


The html below is stored in a selenium WebDriver variable

<td colspan="2" class="pi_mailing_address"><strong>Mailing Address</strong>
        <div>
             <span class="ng-binding">1236 NW 167 ST </span>
             <span ng-show="property.mailingAddress.address2" class="ng-binding ng-hide">STE #</span>
             <span ng-show="property.mailingAddress.address3" class="ng-binding ng-hide">789</span>
             <span ng-show="property.mailingAddress.city" ng-class="{'inline':property.mailingAddress.city}" class="ng-binding inline">OPA LOCKA,</span>
             <span class="inline ng-binding">FL</span>
             <span class="inline ng-binding">33055-4314</span>
             <span ng-hide="isCountryUSA(property.mailingAddress.country)" class="ng-binding"></span>
     </div>
</td>

When I run this

for elem in driver.find_elements_by_xpath('.//span[@class = "ng-binding"]'):
    print(elem.text)

I get 7 values.

I want the 4 value which is: 1236 NW 167 ST

How would I use the DOM hierarchy to only extract the address items so I can assign then to a variables.


Solution

  • To extract the address from the 4th <span> you can use either of the following locator strategies:

    • Using CSS_SELECTOR and nth-child(4):

      print(driver.find_element(By.CSS_SELECTOR, "td.pi_mailing_address > strong +div span:nth-child(4)").text)
      
    • Using CSS_SELECTOR and nth-of-type(4):

      print(driver.find_element(By.CSS_SELECTOR, "td.pi_mailing_address > strong +div span:nth-of-type(4)").text)
      
    • Using XPATH and following:

      print(driver.find_element(By.XPATH, "//strong[text()='Mailing Address']//following::div[1]//following::span[4]").text)
      
    • Using XPATH and following-sibling:

      print(driver.find_element(By.XPATH, "//strong[text()='Mailing Address']//following-sibling::div[1]//following::span[4]").text)
      
    • Note : You have to add the following imports :

      from selenium.webdriver.common.by import By