【问题标题】:web scraping php specific div [duplicate]网页抓取php特定的div [重复]
【发布时间】:2020-06-17 03:10:42
【问题描述】:

首先我知道有很多关于这个的话题,但我没有在其中任何一个中找到解决方案。 我的问题如下,我想用 php 使用“file_get_contents”2 数据从 div 中具有相同名称的站点中提取。 我需要提取数据,然后用 PHP 为每个数据分配一个特定的变量。 无论如何,这里是不返回任何内容的代码 sn-p。

$htmlOficial = file_get_contents('https://www.dolarhoy.com/cotizaciondolaroficial');
preg_match('/<tr><td><a href="#">Banco Nacion</a></td><td class="number">(.*)</td>/', 
$htmlOficial, $ventaOficial);
preg_match('/<tr><td><a href="#">Banco Nacion</a></td><td class="number"></td> <td class="number">(.*)</td>
            </tr>/', 
$htmlOficial, $compraOficial);
$ventaOficial = $ventaOficial[1];
$compraOficial = $compraOficial[1];

该网站是https://www.dolarhoy.com/cotizaciondolaroficial,在“实体”框中显示“Banco Nacion”。我需要一方面提取“购买”数据,另一方面提取“销售”数据

【问题讨论】:

  • 正则表达式中的一个空格不会匹配多个空格和换行符。更简单的选项,顺便说一句:DOM 遍历(有时,虽然不在此处),或 strip_tags() 并仅匹配文本 sn-ps。

标签: php web-scraping preg-match file-get-contents


【解决方案1】:

现已成功测试。有时越简单越好。分而治之,使用explode和一个函数从其他两个字符串之间的文本中获取一个字符串(在您的情况下,您需要具有“数字”类和关闭列标记(td)的表列的内容)。

$htmlOficial = file_get_contents('https://www.dolarhoy.com/cotizaciondolaroficial');

$chunk = strbtw($htmlOficial, 'Banco Nacion', '</tr>');
$number_chunks = explode('class="number"', $chunk);
$ventaOficial = strbtw($number_chunks[1], '>', '</td>');
$compraOficial = strbtw($number_chunks[2], '>', '</td>');

echo "ventaOficial[{$ventaOficial}]<br/>";
echo "compraOficial[{$compraOficial}]<br/>";

function strbtw($text, $str1, $str2="", $trim=true) {
    $len = strlen($str1);
    $pos_str1 = strpos($text, $str1);
    if ($pos_str1 === false) return "";
    $pos_str1+=$len;

    if (empty($str2)) { // try to search up to the end of line
        $pos_str2 = strpos($text, "\n", $pos_str1);
        if ($pos_str2 === false) $pos_str2 = strpos($text, "\r\n", $pos_str1);
    }
    else $pos_str2 = strpos($text, $str2, $pos_str1);

    if ($pos_str2 !== false) {
        if ($pos_str2-$pos_str1 === 0) $rez = substr($text, $pos_str1);
        else $rez = substr($text, $pos_str1, $pos_str2-$pos_str1);
    }
    else $rez = substr($text, $pos_str1);

    return ($trim) ? trim($rez) : ($rez);
}

如果有效,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多