2 回答
TA贡献1810条经验 获得超4个赞
如果我正确理解你的问题,这就是你要找的。
let labels = document.querySelectorAll(".sc-account-rows__row__label");
[...labels].forEach(label => {
if (label.innerText === "RTF") {
let price = label.parentElement.querySelector(".sc-account-rows__row__price").innerText;
console.log(price);
}
})
Console: "-$ 1.485"
如果您需要使用除 RTF 之外的额外标签:
let words = ["RTF", "something", "else"];
// change if condition to
if (words.includes[label.innerText]) {...}
TA贡献1817条经验 获得超6个赞
另一种方法是使用 XPath,这是一种旧的 XML 导航标准,也适用于 HTML。在本例中,您正在寻找一个类div
为“sc-account-rows__row__price”的类,它div
附近有另一个类为“sc-account-rows__row__label”且文本为“RTF”的类。
div 的 XPath 是
//div[@class="sc-account-rows__row__label"][text()="RTF"]/following-sibling::div[@class="sc-account-rows__row__price--container"]//div[@class="sc-account-rows__row__price"]
由于 price--container/price 的嵌套性质,它有点复杂div
。
要获取文本,您将使用document.evaluate
:
function getPriceByLabel(label) {
// change this to a parent element if you can; it will speed up the process.
const contextNode = document;
const priceResults = document.evaluate(`//div[@class="sc-account-rows__row__label"][text()="${label}"]/following-sibling::div[@class="sc-account-rows__row__price--container"]//div[@class="sc-account-rows__row__price"]`, contextNode, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null);
const priceElement = priceResults.singleNodeValue;
const price = priceElement.textContent;
return price;
}
console.log(getPriceByLabel("RTF"));
console.log(getPriceByLabel("some text"));
<li class="sc-account-rows__row">
<div class="sc-account-rows__row__label">RTF</div>
<div class="sc-account-rows__row__price--container">
<div class="sc-account-rows__row__price">-$ 1.485</div>
</div>
</li>
<li class="sc-account-rows__row">
<div class="sc-account-rows__row__label">some text</div>
<div class="sc-account-rows__row__price--container">
<div class="sc-account-rows__row__price">-$ 2.418</div>
</div>
</li>
我把它放在一个带有标签并吐出价格的函数中。
添加回答
举报