如何使用 Selenium webdriver 定位嵌套元素?
我有以下 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上 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').