使用“SimpleHTMLDOM”获取span内容


Getting span contents with “Simple HTML DOM”

我正试图使用"简单HTML DOM"从用户页面中抓取Twitter推文。

我可以得到推文,但不能得到它们的时间戳。

HTML看起来是这样的:

<p class="ProfileTweet-text js-tweet-text u-dir" lang="en" dir="ltr" data-aria-label-part="0">Tweet content<a href="/hashtag/TweetContent?src=hash" data-query-source="hashtag_click" class="twitter-hashtag pretty-link js-nav" dir="ltr" ><s>#</s><b>TweetContent</b></a> <a href="http://t.co/JFredfvgYs" class="twitter-timeline-link u-hidden" data-pre-embedded="true" dir="ltr" >pic.twitter.com/JFredfvgYs</a></p>

UNIX时间戳如下:

<span class="js-short-timestamp "
    data-aria-label-part="last"
    data-time="1411584273"
    data-long-form="true" >
    Sep 24
  </span>

所以我在做:

<?php
include 'simple_html_dom.php';
$html = file_get_html('https://twitter.com/UserName');
$tweets = $html->find('div.ProfileTweet-contents');
foreach ($tweets as $tweet) {
$tweetText = $tweet->find('p.ProfileTweet-text', 0)->plaintext;
echo $tweetText;
}
?>

这对于获取推文文本很好,但我不知道如何获取Unix时间戳。

我想也许:

<?php
include 'simple_html_dom.php';
$html = file_get_html('https://twitter.com/UserName');
$tweets = $html->find('div.ProfileTweet-contents');
foreach ($tweets as $tweet) {
$tweetText = $tweet->find('p.ProfileTweet-text', 0)->plaintext;
$tweetDate = $tweet->find('span.js-short-timestamp ', 0);
echo $tweetText.' '.$tweetDate->data-time;
?>

但这都错了。有什么帮助吗?

很可能是因为您试图访问的属性。用这个包装了炒作的属性:

$tweetDate->{'data-time'};

粗略示例:

$html = file_get_html('https://twitter.com/katyperry');
$tweet_block = $html->find('div.ProfileTweet');
foreach($tweet_block as $tweet) {
    // get tweet text
    $tweetText = $tweet->find('p.ProfileTweet-text text', 0)->innertext;
    echo 'Tweet: ' . $tweetText . '<br/>';
    // get tweet stamp
    $tweetDate = $tweet->find('a.ProfileTweet-timestamp span.js-short-timestamp', 0);
    echo 'Timestamp: ' .$tweetDate->{'data-time'} . '<br/>';
    echo '<hr/>';
}