2

5回以上「いいね」された投稿を抽出するこのクエリがあります。

//div[@class="pin"]
[.//span[@class = "LikesCount"]
[substring-before(normalize-space(text())," ") > 5]

タイトル、画像の URL、番号、リピン番号などの追加情報を抽出して保存したいと思います...

それらをすべて抽出する方法は?

  • 複数の XPath クエリ?
  • php と php 関数を繰り返しながら、結果の投稿のノードを掘り下げますか?
  • ...

マークアップの例に従います。

<div class="pin">

<p class="description">gorgeous couch <a href="#">#modern</a></p>

[...]

<div class="PinHolder">
<a href="/pin/56787645270909880/" class="PinImage ImgLink">
    <img src="http://media-cache-ec3.pinterest.com/upload/56787645270909880_d7AaHYHA_b.jpg" 
         alt="Krizia" 
         data-componenttype="MODAL_PIN" 
         class="PinImageImg" 
         style="height: 288px;">
</a>
</div>

<p class="stats colorless">
    <span class="LikesCount"> 
        22 likes 
    </span>
    <span class="RepinsCount">
        6 repins
    </span>
</p>

[...]

</div>
4

1 に答える 1

2

コードですでにXPathを使用しているので、XPathを使用してその情報を抽出することをお勧めします。説明を抽出する方法の例を次に示します。

<?php 

// will store the posts as assoc arrays
$mostLikedPostsArr = array();

// call your fictional load function
$doc = load_html('whatever');

// create a XPath selector
$selector = new DOMXPath($doc);

// this your query from above
$query = '//div[@class="pin"][.//span[@class = "LikesCount"][substring-before(normalize-space(text())," ") > 5]';

// getting the most liked posts
$mostLikedPosts = $selector->query($query);

// now iterate through the post nodes
foreach($mostLikedPosts as $post) {

    // assoc array for a post
    $postArr = array();

    // you can do 'relative' queries once having a reference to $post
    // note $post as the second parameter to $selector->query()

    // lets extract the description for example
    $result = $selector->query('p[@class = "description"]', $post);
    // just using nodeValue might be ok for text only nodes.
    // to properly flatten the <a> tags inside the descriptions 
    // it will take further attention.
    $postArr['description'] = $result->item(0)->nodeValue;

    // ...

    $mostLikedPostsArr []= $postArr;
}
于 2012-12-17T14:18:56.943 に答える