【问题标题】:Php Scraping - How do I catch the variable in the source code?Php Scraping - 如何在源代码中捕获变量?
【发布时间】:2017-07-21 21:29:10
【问题描述】:

在下面的 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);

?>

【问题讨论】:

  • 有什么问题?
  • 因此,使用 DOM 解析器读取 html 标记,然后选择您喜欢的任何内容。正则表达式不太适合解析 html...
  • 除此之外:您的代码工作得非常好。 $results[1] 保存字符串 1.31
  • @Martin,我使用的代码无法捕捉到这个变量
  • 当然,它是在$results[1] 中捕获的,这是一个将字符串作为单个元素完全保存的数组。之所以是数组,是因为你使用preg_match_all()而不是preg_match()。我在下面的答案中指出了这一点。

标签: php web screen-scraping


【解决方案1】:

您的代码运行良好,不过我建议您稍作修改:

<?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 "

更新:

正如您在下面的 cmets 中指出的那样,如果您不使用示例中所示的静态标记(出于演示目的)您实现了一个内部 http 请求,从某个如您在问题中所示的远程服务器。

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

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

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

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

【讨论】:

  • 非常感谢!
  • 当我使用 file_get_contents 时,给出结果“Array()”。那么,如何在不使用标记的情况下运行?
  • @CanKorkmaz 听起来你又用了preg_match_all() 而不是preg_match()...
  • 不,我不 :) oyunfor.com/knight-online/gb-gold-bar"; $url_connect = file_get_contents($url); preg_match('@
    (.*?)
  • 然后检查 $result 和您从内部请求作为标记收到的有效负载中究竟包含什么。请将此类信息作为“更新”添加到问题本身。谢谢。
猜你喜欢
相关资源
最近更新 更多
热门标签