【问题标题】:Getting span contents with “Simple HTML DOM”使用“简单 HTML DOM”获取 span 内容
【发布时间】:2014-11-10 14:44:12
【问题描述】:

我正在尝试使用“简单 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;
?>

...但那都是错误的。有什么帮助吗?

【问题讨论】:

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


    【解决方案1】:

    很可能是因为您尝试访问该属性。用这个包裹那个被炒作的属性:

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

    【讨论】:

    • 是的! (粗略地)包装连字符的属性有效!非常感谢先生!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多