使用“Simple HTML DOM”获取span内容

时间:2014-11-10 14:44:13

标签: php html web-scraping simple-html-dom

我试图使用“Simple 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;
?>

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

1 个答案:

答案 0 :(得分:3)

很可能是因为您尝试访问该属性。用这个包裹着那个夸张的财产:

$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/>';
}