使用xpath获取div类标题内容文本

时间:2015-12-27 11:25:38

标签: html xpath

我要求获得以下文字"电子艺术" (这可以根据数据改变)使用类标题"提供者" (使用Xpath,这个类对所有人来说都是一样的)。我尝试了各种xpath编码,但无法获得我想要的结果。我真的很想找点帮助。

<div class="meta-info"> 
<div class="title"> Offered By</div> 
<div class="content">ELECTRONIC ARTS</div> </div>

2 个答案:

答案 0 :(得分:1)

这是一个可能的XPath表达式,然后您可以根据需要简化或添加更多条件(XPath格式化为更易读):

//div[
    @class='meta-info' 
        and 
    div[@class='title' and normalize-space()='Offered By']
]/div[@class='content']

解释:

  • //div[@class='meta-info' and ...:查找div元素class属性值等于"meta-info"和...

  • div[@class='title' and normalize-space()='Offered By']]:...包含子元素div,其中class属性值等于"title"且内容等于"Offered By"

    < / LI>
  • /div[@class='content']:来自此类div<div class="meta-info">要明确),返回子元素div,其中class属性值等于{{ 1}}

答案 1 :(得分:0)

使用Mozilla上的示例:

&#13;
&#13;
var xpath = document.evaluate("//div[@class='content']", document, null, XPathResult.STRING_TYPE, null);

document.write('The text found is: "' + xpath.stringValue + '".');
console.log(xpath);
&#13;
<div class="meta-info"> 
  <div class="title"> Offered By</div> 
  <div class="content">ELECTRONIC ARTS</div>
</div>
&#13;
&#13;
&#13;

顺便说一句,我认为document.querySelectordocument.querySelectorAll在这种情况下更方便:

&#13;
&#13;
var content = document.querySelector('.meta-info .content').innerText;

document.write('The text found is: "' + content + '".');
console.log(content);
&#13;
<div class="meta-info"> 
  <div class="title"> Offered By</div> 
  <div class="content">ELECTRONIC ARTS</div>
</div>
&#13;
&#13;
&#13;

相关问题