【发布时间】:2020-07-03 03:58:48
【问题描述】:
我有一个包含一些链接的 HTML 文档,我正在尝试使用 XPATH 来选择包含 AIG 公司网站的链接。
<a class="cmp-CompanyLink"
href="http://www.aig.com/careers"
target="_blank"
rel="nofollow noopener"
data-tn-link="redirect"
data-tn-element="companyLink"
>AIG website</a>
这里是 HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Hello Plunker!</h1>
<div class="cmp-AboutMetadata-itemInner">
<div class="cmp-AboutMetadata-itemTitle">Website</div>
<div class="cmp-AboutMetadata-itemCotent">
<a
class="cmp-CompanyLink"
href="https://twitter.com/AIGinsurance"
target="_blank"
rel="nofollow noopener"
data-tn-link="redirect"
data-tn-element="companyLink"
>Twitter</a
>
<br />
<a
class="cmp-CompanyLink"
href="https://www.facebook.com/AIGInsurance"
target="_blank"
rel="nofollow noopener"
data-tn-link="redirect"
data-tn-element="companyLink"
>Facebook</a
>
<br /><a
class="cmp-CompanyLink"
href="https://twitter.com/AIGinsurance"
target="_blank"
rel="nofollow noopener"
data-tn-link="redirect"
data-tn-element="companyLink"
>Twitter</a
><br /><a
class="cmp-CompanyLink"
href="https://www.facebook.com/AIGInsurance/"
target="_blank"
rel="nofollow noopener"
data-tn-link="redirect"
data-tn-element="companyLink"
>Facebook</a
><br /><a
class="cmp-CompanyLink"
href="https://www.linkedin.com/company/aig"
target="_blank"
rel="nofollow noopener"
data-tn-link="redirect"
data-tn-element="companyLink"
>LinkedIn</a
><br /><a
class="cmp-CompanyLink"
href="https://www.instagram.com/aigrugby/"
target="_blank"
rel="nofollow noopener"
data-tn-link="redirect"
data-tn-element="companyLink"
>Instagram</a
><br /><a
class="cmp-CompanyLink"
href="https://www.youtube.com/user/AIG"
target="_blank"
rel="nofollow noopener"
data-tn-link="redirect"
data-tn-element="companyLink"
>YouTube</a
><br /><a
class="cmp-CompanyLink"
href="http://www.aig.com/careers"
target="_blank"
rel="nofollow noopener"
data-tn-link="redirect"
data-tn-element="companyLink"
>AIG website</a
><br /><a
data-tn-action-click="true"
data-tn-element="less-link"
href="#"
>less</a
>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
这是我的 JavaScript 代码and the plunker:
var link = document.evaluate("//а[@class='cmp-CompanyLink' and contains(text(), 'website')]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
document.body.innerHTML += "<br />Result:<br />";
document.body.innerHTML += link.singleNodeValue;
if(link.singleNodeValue){
const result = "<br /> found: " + link.singleNodeValue.textContent;
document.body.innerHTML += result;
}
我不确定这里有什么错误。关于为什么链接为空的任何想法?如何获取正确的节点?
【问题讨论】:
标签: javascript dom xpath