我正在嘗試從包含特定字串的網頁中檢索元素串列。我正在使用 selenium 評估 XPath ISearchContext.FindElement(By.XPath(...)),因此 XPath 引擎是瀏覽器支持的引擎。
下面是我創建的最小示例頁面,但在現實世界的場景中,我無法修改頁面的結構:
<html lang="en">
<head>
<title></title>
</head>
<body>
<nav>
<ul>
<li>Nav Item 1</li>
<li>Nav Item 2</li>
</ul>
</nav>
<main>
<div class="content">
<p class="description">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab deserunt dolore eius est
facere incidunt magni
minus molestiae natus, nesciunt nostrum, officia perspiciatis placeat provident reiciendis saepe sed, sit
voluptates.</p>
<p class="price">1.150<span class="comma">,</span><sup>00</sup> <span class="currency">EUR</span></p>
</div>
<aside>
<p class="price">1.150<span class="comma">,</span><sup>00</sup> <span class="currency">EUR</span></p>
</aside>
<footer>
1<span>.</span>150<span class="comma">,</span><sup>00</sup> <span class="currency">EUR</span>
</footer>
</main>
</body>
</html>
我正在尋找的元素是[p.price, p.price, footer];基本上只有包含字串的“最深”元素1.150,00 EUR。
如果我在 Chrome 的開發者工具控制臺中評估以下 XPath
$x("//*[contains(., '1.150,00 EUR')][contains(ancestor::*, '1.150,00 EUR')][not(contains(child::*, '1.150,00 EUR'))]")
我得到的結果是[body, div.content, p.price, p.price, footer]。
我正在尋找一種仍然讓我留在 Selenium 背景關系中的解決方案,以便我可以進一步訪問元素屬性(例如元素位置)。它不一定必須涉及 XPath,我也愿意使用其他瀏覽器。
uj5u.com熱心網友回復:
//*[contains(., '1.150,00 EUR')]
[not(
*[contains(., '1.150,00 EUR')]
)]
= "文本值包含 '1.150,00 EUR' 且沒有文本值包含 '1.150,00 EUR' 的子元素的所有元素"
uj5u.com熱心網友回復:
給定 HTML 樹,這個 xpath 選擇請求的元素
$x("//*[.='EUR']/parent::*[contains(., '1.150,00 EUR')]")
結果
Array(3) [ p.price, p.price, footer ]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/520749.html
