如何从给定WebElement中提取latitude(纬度)和longitude(经度)?
提取WebElement中的纬度和经度
先看目标元素的HTML结构:
<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>
方法1:用Selenium直接定位子元素
如果是用Selenium获取到的这个WebElement,直接定位内部的geo:lat和geo:long标签即可:
- 用XPath定位:
# 假设已获取到目标span元素,赋值给geotag_element latitude = geotag_element.find_element(By.XPATH, ".//geo:lat").text longitude = geotag_element.find_element(By.XPATH, ".//geo:long").text - 或者直接通过标签名定位:
latitude = geotag_element.find_element(By.TAG_NAME, "geo:lat").text longitude = geotag_element.find_element(By.TAG_NAME, "geo:long").text
方法2:解析元素HTML文本(兼容更多场景)
如果直接定位子元素遇到问题,可以先获取元素的HTML内容,再通过字符串处理或解析库提取:
简单字符串提取(适合结构固定的情况)
html_content = geotag_element.get_attribute("innerHTML") # 提取纬度 lat_start = html_content.find("<geo:lat>") + len("<geo:lat>") lat_end = html_content.find("</geo:lat>") latitude = html_content[lat_start:lat_end].strip() # 提取经度 long_start = html_content.find("<geo:long>") + len("<geo:long>") long_end = html_content.find("</geo:long>") longitude = html_content[long_start:long_end].strip()
用BeautifulSoup解析(更健壮)
from bs4 import BeautifulSoup html_content = geotag_element.get_attribute("innerHTML") soup = BeautifulSoup(html_content, "html.parser") latitude = soup.find("geo:lat").text.strip() longitude = soup.find("geo:long").text.strip()
内容的提问来源于stack exchange,提问作者Ezra Mendelson
相关产品推荐
相关产品推荐

