如何使用 Selenium webdriver 定位嵌套元素?

发布于 2025-01-15 14:03:38 字数 866 浏览 0 评论 0原文

我有以下 html:

<label class="control-label col-sm-4" for="bla-bla">
   "Value date"
   ::after
</label>
<div class="col-sm-8">
   <div class="row">
      ::before
      <div class="col-sm-2>
         <label class="control-label" for="bla-bla">
            "Priority"
            ::after
         </label>
      </div>
      ::after
   </div>
   ::after
</div>

我需要提取“起息日期”和“优先级”等元素。 这是我当前的解决方案:

elements = [f for f in driver.find_elements(By.XPATH, "//*[contains(@class, 'control-label')]")]

它与“起息日期”等元素完美配合,但看不到“优先级”元素。我看到“优先级”嵌套在此处的“起息日期”元素中。也许,它会以某种方式影响 XPATH 的工作方式。 我尝试添加精确的类匹配,但没有任何结果:

elements = [f for f in driver.find_elements(By.XPATH, "//*[contains(@class, 'control-label') or @class = 'control-label']")]

I have the following html:

<label class="control-label col-sm-4" for="bla-bla">
   "Value date"
   ::after
</label>
<div class="col-sm-8">
   <div class="row">
      ::before
      <div class="col-sm-2>
         <label class="control-label" for="bla-bla">
            "Priority"
            ::after
         </label>
      </div>
      ::after
   </div>
   ::after
</div>

I need to extract both the elements like "Value date" and the "Priority" element.
Here is my current solution:

elements = [f for f in driver.find_elements(By.XPATH, "//*[contains(@class, 'control-label')]")]

It works perfectly with the elements like "Value date", but it doesn't see the "Priority" element. I see that "Priority" is nested in the "Value date" element here. Maybe, it somehow affects the way XPATH works.
I tried adding the exact class match, but without any result:

elements = [f for f in driver.find_elements(By.XPATH, "//*[contains(@class, 'control-label') or @class = 'control-label']")]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

恬淡成诗 2025-01-22 14:03:38

实际上 XPATH 工作正常。问题出在我接下来对找到的元素所做的事情。我使用 .text() 方法提取文本,但该方法并不总是按预期工作。如果您遇到类似问题,请尝试使用 .get_attribute('innerText') 和 .get_attribute('textContent')。

Actually the XPATH was working OK. The problem was in what I was doing with the found elements next. I was extracting text by using the .text() method which doesn't always work as expected. If you experience similar problems, try using .get_attribute('innerText') and .get_attribute('textContent').

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文