Php Scraping - 如何在源代码中捕获变量?

时间:2017-07-21 21:29:11

标签: php web screen-scraping

在下面的html代码中,我想要捕获变量" 1.31"。谢谢你的帮助。

Source Code
    <div style="font-size:20px">1.31 <i class="fa fa-try"></i> <span style="text-decoration: line-through; color:#919191; font-size: 14px; margin-top: 7px; margin-right: 5px; float:left" itemprop="price" content="1.55">1.55 <i class="fa fa-try" itemprop="priceCurrency" content="TL"></i></span>
    <link itemprop="availability" href="http://schema.org/InStock">
    </div>

<?php

$url = "https://www.oyunfor.com/knight-online/gb-gold-bar";

$url_connect = file_get_contents($url);

preg_match('@<div style="font-size:20px">(.*?)<i@si',$url_connect,$results);

print_r($results);

?>

1 个答案:

答案 0 :(得分:0)

您的代码完全正常,但我建议稍作修改:

<?php
$markup = <<<HTML
    <div style="font-size:20px">1.31 <i class="fa fa-try"></i> <span style="text-decoration: line-through; color:#919191; font-size: 14px; margin-top: 7px; margin-right: 5px; float:left" itemprop="price" conten
    <link itemprop="availability" href="http://schema.org/InStock">
    </div>
HTML;

preg_match('@<div style="font-size:20px">(.*?)<i@si', $markup, $results);
var_dump($results[1]);

输出是:

string(5) "1.31 "

更新:

正如您在下面的评论中指出的那样, not 得到预期的结果如果不是使用静态标记,如示例所示,为了演示目的,您实现了一个内部http请求,从某些内容获取该标记您在问题中显示的远程服务器。

原因是您以这种方式收到的标记与您在问题中提供的示例不符。它略有不同,导致您的正则表达式不匹配。这就是为什么正则表达式被认为是解析这种标记的一种不好的方法的主要原因:它们在主题标记发生一些微小变化时容易破解。

更具体地说:您收到的标记实际上是无效的。您可能没有意识到这一点,因为您在浏览器中将其可视化。但请注意,浏览器会尝试“修复”以使其可用。对于调试,您需要查看没有这些中间层的内容,以了解您实际处理的内容。在这里,您应该将收到的标记转储到某个日志文件中。

无论如何:你可以稍微修改你的正则表达式,让它再次匹配。这就是我的建议,使用它会再次产生相同的输出,如上所示。

@<div\s+[^>]*style="?font-size:20px"?[^>]*>(.*?)<i@si