You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium如何通过DOM层级精准提取指定class的目标span元素

精准提取DOM中的地址元素并赋值变量

问题背景

你有如下HTML结构:

<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>

执行这段Selenium代码后会得到7个输出:

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

需求是精准提取内容为「1236 NW 167 ST」的span元素,并将各地址项分别赋值给变量。


解决方案

一、精准定位目标span元素(「1236 NW 167 ST」)

1. 利用DOM层级+索引定位

目标元素是包裹地址的<div>下的第一个span,直接通过父容器定位第一个子元素:

# 获取地址第一行
address_line1 = driver.find_element_by_xpath('.//td[@class="pi_mailing_address"]/div/span[1]').text.strip()

2. 结合文本内容定位

如果文本内容固定,直接通过文本匹配:

address_line1 = driver.find_element_by_xpath('.//span[@class="ng-binding" and contains(text(), "1236 NW 167 ST")]').text.strip()

3. 过滤隐藏元素

原HTML中有带ng-hide类的隐藏元素,只取可见的第一个span:

address_line1 = driver.find_element_by_xpath('.//td[@class="pi_mailing_address"]/div/span[@class="ng-binding" and not(contains(@class, "ng-hide"))][1]').text.strip()

二、提取所有地址项并赋值变量

一次性定位所有可见地址元素,按顺序赋值:

# 定位所有可见的地址span元素
address_elements = driver.find_elements_by_xpath('.//td[@class="pi_mailing_address"]/div/span[contains(@class, "ng-binding") and not(contains(@class, "ng-hide"))]')

# 按顺序赋值
address_line1 = address_elements[0].text.strip()
city = address_elements[1].text.strip().rstrip(',')  # 去除城市名末尾的逗号
state = address_elements[2].text.strip()
zip_code = address_elements[3].text.strip()

如果要更严谨,也可以结合每个元素的Angular属性单独定位:

# 单独定位各地址项
address_line1 = driver.find_element_by_xpath('.//td[@class="pi_mailing_address"]/div/span[not(@ng-show)][1]').text.strip()
city = driver.find_element_by_xpath('.//td[@class="pi_mailing_address"]/div/span[@ng-show="property.mailingAddress.city"]').text.strip().rstrip(',')
state = driver.find_element_by_xpath('.//td[@class="pi_mailing_address"]/div/span[@class="inline ng-binding" and not(@ng-show)][1]').text.strip()
zip_code = driver.find_element_by_xpath('.//td[@class="pi_mailing_address"]/div/span[@class="inline ng-binding" and not(@ng-show)][2]').text.strip()

内容的提问来源于stack exchange,提问作者Leo Torres

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 05:23:23