xpath如何选择html内容?

抱歉 真的是很小白的问题,不过我确实是查了很多天;这个问题还在困扰着我请大神帮忙看看

我要爬去http://news.ci123.com/article...这个页面中的内容,即图片描述
如果带html应该如何写Xpath 如何不带html应该如何写?

//*[@id='post']/div[2]/这个代码只能抓取到‘http://news.ci123.com/uploads...

    array(
        'name' => "neirong",
        'selector' => "//*[@id='post']/div[2]/",
        'required' => true,
    ),
阅读 7.6k
2 个回答

不帶HTML標籤

$x("//div[@class='info']/div/text()")

clipboard.png

帶HTML標籤

$x("//div[@class='info']/div")

同理,若要找其他區塊

$x('//div[@class = "entry group"]')

console回傳[div.entry.group]為一個元素的陣列

取其唯一元素的innerHTML

$x('//div[@class = "entry group"]')[0].innerHTML

結果

"
                            <p><img class="aligncenter size-full wp-image-106599" title="10" src="http://news.ci123.com/uploads/2017/05/2017-05-19-11390495.jpeg" alt="" width="630" height="200"></p>
<p>这两天,一个十八线小明星因为被老婆起诉离婚红了,他就是至上励合成员刘洲成。他的妻子林苗控诉他恶性家暴,曾把自己打流产。本期《育姐聊八卦》让我们来“长见识”。......(以下略)"

若使用innerText

$x('//div[@class = "entry group"]')[0].innerText

結果

"
这两天,一个十八线小明星因为被老婆起诉离婚红了,他就是至上励合成员刘洲成。他的妻子林苗控诉他恶性家暴,曾把自己打流产。本期《育姐聊八卦》让我们来“长见识”。



01

没有最渣,只有更渣。


反正php DOMXPath 返回的是 DOMNode 的集合, 所以强求要在 xpath 中获取text 和 html 感觉没有意义

//http://www.php.net/manual/en/book.dom.php
$config = array(
    'name' => "neirong",
    'selector' => "//*[@id=\"post\"]/div[2]",
    'required' => true,
);

$url = "http://news.ci123.com/article/106582.html";

$html_string = file_get_contents($url);
$document = new DOMDocument(1.0);
$document->loadHTML($html_string);

$xpath = new DOMXPath($document);
$nodeList = $xpath->query($config['selector']);

foreach ($nodeList as $index => $node){
    echo $node->textContent; //不包含HTML标签
    echo "<br/>";
    echo $node->ownerDocument->saveHTML($node); //包含HTML标签
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题