【问题标题】:Scrape a statistic from YouTube using PHP使用 PHP 从 YouTube 上抓取统计信息
【发布时间】:2012-12-02 00:56:22
【问题描述】:

在尝试独自完成这件事 3 小时后,我决定自己做这件事是不可能或不可能的。我的问题如下:

如何使用 PHP 抓取附件图像中的数字以在网页中回显它们?

图片网址:http://gyazo.com/6ee1784a87dcdfb8cdf37e753d82411c

请帮忙。我几乎尝试了所有方法,从使用 cURL 到使用正则表达式,再到尝试 xPath。没有什么是正确的。

我只想要数字本身,以便将它们隔离,分配给一个变量,然后在页面的其他地方回显。

更新:

http://youtube.com/exonianetwork - 我要抓取的 URL。

/html/body[@class='date-20121213 en_US ltr   ytg-old-clearfix guide-feed-v2 site-left-aligned exp-new-site-width exp-watch7-comment-ui webkit webkit-537']/div[@id='body-container']/div[@id='page-container']/div[@id='page']/div[@id='content']/div[@id='branded-page-default-bg']/div[@id='branded-page-body-container']/div[@id='branded-page-body']/div[@class='channel-tab-content channel-layout-two-column selected   blogger-template ']/div[@class='tab-content-body']/div[@class='secondary-pane']/div[@class='user-profile channel-module yt-uix-c3-module-container ']/div[@class='module-view profile-view-module']/ul[@class='section'][1]/li[@class='user-profile-item '][1]/span[@class='value']

我尝试过的 xPath,由于某种未知原因无法正常工作。没有抛出异常或错误,也没有显示任何内容。

【问题讨论】:

  • 您的 xPath 查询是什么?为什么它不起作用?
  • 我已经用该信息更新了原始帖子。
  • 图像图像识别软件。 SO 问题here 建议了一个可能有效的 PHP 工具。
  • 我不想要图像中的数字。我想要网页上的数字,图片仅供参考。

标签: php xpath curl youtube scrape


【解决方案1】:

也许一个简单的 XPath 会更容易操作和调试。

这是Short Self-Contained Correct Example(注意class 名称末尾的空格):

#!/usr/bin/env php

<?
$url = "http://youtube.com/exonianetwork";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html = curl_exec($ch);
if (!$html)
{
    print "Failed to fetch page. Error handling goes here";
}
curl_close($ch);

$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$profile_items = $xpath->query("//li[@class='user-profile-item ']/span[@class='value']");

if ($profile_items->length === 0) {
    print "No values found\n";
} else {
    foreach ($profile_items as $profile_item) {
        printf("%s\n", $profile_item->textContent);
    }
}

?>

执行:

% ./scrape.php

57
3,593
10,659,716
113,900
United Kingdom

【讨论】:

  • 完美!只需对我的设置进行一些调整,我就可以将它推到数组的末尾,这样我就可以单独调用这些值了 :) 谢谢!
【解决方案2】:

如果您愿意再次尝试正则表达式,则此模式应该可以工作:

!Network Videos:</span>\r\n +<span class=\"value\">([\d,]+).+Views:</span>\r\n +<span class=\"value\">([\d,]+).+Subscribers:</span>\r\n +<span class=\"value\">([\d,]+)!s

它使用嵌入的逗号捕获数字,然后需要将其删除。我对PHP不熟悉,所以不能给你更完整的代码

【讨论】:

    猜你喜欢
    • 2021-04-06
    • 2019-12-30
    • 2011-09-08
    • 1970-01-01
    • 2017-12-06
    • 2021-01-23
    • 1970-01-01
    • 2015-10-03
    • 2013-01-16
    相关资源
    最近更新 更多