php - 使用 “Simple HTML DOM” 获取跨度内容

标签 php html web-scraping 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/>';
}

关于php - 使用 “Simple HTML DOM” 获取跨度内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26846309/

相关文章:

php - 单击 "back"按钮后防止重新提交表单

php - 根据月份或年份拆分日期数组

javascript - 如何在保持其响应式设计能力的同时使用 flexbox 重叠图像

php - 如何在 html 文件中搜索简单字符串?

php - 如果只有同一用户会看到 XSS 输入是否构成威胁?

php - 如何在 php 中使用密码保护 zip?

HTML 电子邮件不适用于 Gmail

python - 合并两个包含列表的对象列表

css - xpath 在 r 中进行网页抓取时返回空文本

python - headless Chrome 驱动程序不适用于 Selenium