skip to Main Content

I have the following WebElement. How can I extract the latitude and longitude?

       <span class="geotag" xmlns:geo="//www.w3.org/2003/01/geo/wgs84_pos#">
        (<geo:lat>40.75198</geo:lat>,<geo:long>-73.96978</geo:long>)
    </span>

2

Answers


  1. One way would be the following:

    const tag = document.querySelector(".geotag")
    
    let latitude
    let longitude
    if (tag.children[0].tagName.toLowerCase() === "geo:lat") {
      latitude = tag.children[0].innerText
      longitude = tag.children[1].innerText
    } else {
      latitude = tag.children[1].innerText
      longitude = tag.children[0].innerText
    }
    
    console.log(latitude, longitude)
    <span class="geotag" xmlns:geo="//www.w3.org/2003/01/geo/wgs84_pos#">
      (<geo:lat>40.75198</geo:lat>,<geo:long>-73.96978</geo:long>)
    </span>

    You select the element, then check which of the children is the latitude and which is the longitude. Then set the variables accordingly.

    Of course, the selection of the element could be made easier, if it had a unique ID instead of only a class.

    Login or Signup to reply.
  2. Check the below code with explanation:

    # Below line will store the desired element text
    element = WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.XPATH, "//span[@class='geotag']"))).text
    # Below 2 lines will strip the open and closed braces
    element = element.rstrip(')')
    element = element.lstrip('(')
    # Below line will split the string by ','
    split = element.split(',')
    # Store first index of array
    latitude = split[0]
    # Store second index of array
    longitude= split[1]
    # Print
    print("latitude = " + latitude)
    print("longitude= " + longitude)
    

    Console output:

    latitude = 40.75198
    longitude= -73.96978
    

    Imports required:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.ui import WebDriverWait
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search