【发布时间】: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