首页 > 解决方案 > 使用 XPath 选择子元素的父元素

问题描述

在开始编写本文中包含的源代码之前,我已将所有敏感数据替换为字符串“x”。

<div class="pod productPod icon-life clearFix nonwrap"
     id="xxxxxxxxxx"
     internalid="xxxxxxxxxx"
     data-properties-type="xxxxxxxxxx"
     data-properties-code="xxxxxxxxxx"
     data-properties-loaded="False"
     data-properties-url="xxxxxxxxxx"
     data-properties-showmaintenanceerrormessage="False"
     data-properties-product-type="xxxxxxxxxx">
  <span class="podTitle">Your policies</span>
  <div id="1" class="productPodInner" data-qa-productpod="">
    <span class="notificationBubble fullProdLarge" aria-hidden="true"></span>
    <h2><a data-feedback="" class="clearFix roundelLink" href="#productId0" data-roundel-id="0">
      <span class="productIconWrapper">
        <span class="productIcon">
        </span>
      </span>
      <span class="productData">
        <span class="productName" style="min-height: auto;">Protection</span>
        <span class="notificationBubble fullProd"></span>
      </span>
    </a></h2>

    <div class="productDetails podContent" id="#productId0" style="width: 1903px; left: -306.703px;">
      <div class="productDetailsInner clearFix">
        <h3>xxxxxxxxxx</h3>
        <!-- TODO:: Display this in the 2nd column-->
        <dl class="initialPolicyContainer detailsList" style="display: none;">
          <dt>Policy Number</dt>
          <dd class="initialPolicyNumber" data-qa-text="xxxxxxxxxx">xxxxxxxxxx</dd>
        </dl>
        <div class="clearFix variant3Container" style=""><div class="group-1-2 clearFix">
          <div class="column">
            <dl class="detailsList">
              <dt>Policy number</dt>
              <dd class="policyNumberVal">xxxxxxxxxx</dd>
              <dt>Term</dt>
              <dd>xxxxxxxxxx</dd>
            </dl>

所以我的目标是能够使用 Xpath 定位器选择顶级父级,然后使用 selenium 单击它。

在网站上有一个包含多个圆形部分的 pod,每个部分都包含自己的策略。通常我可以使用通过 policyType(text) 找到 roundel 的 Xpath 查询来选择一个 roundel,但是如果有 2 个策略具有相同的 policyType,那么这个 Xpath 定位器只会找到第一个。

Roundel 有一个独特的 policyNumberVal(第 29 行)

<dd class="policyNumberVal">xxxxxxxxxx</dd>

我可以使用这个 Xpath 找到:

//dd[@class='policyNumberVal' and text() = '{policyNumber}']

我想知道的是,一旦我找到了“policyNumberVal”,我该如何加强并选择父母?

如果您需要更多信息,请告诉我。

标签: c#htmlxmlselenium-webdriverxpath

解决方案


您可以使用parent轴,

//dd[@class='policyNumberVal' and text() = '{policyNumber}']/parent::*

它的缩写,

//dd[@class='policyNumberVal' and text() = '{policyNumber}']/..

或者,提升谓词并直接选择父级:

//dl[dd[@class='policyNumberVal' and text() = '{policyNumber}']]

推荐阅读