我使用php网页抓取,我想在周日从下面的html代码中获取价格(3.65):
<tr class="odd">
<td >
<b>Sunday</b> Info
<div class="test">test</div>
</td>
<td>
€ 3.65 *
</td>
</tr>
但是我没有找到最好的正则表达式来做到这一点......我使用这个php代码:
<?php
$data = file_get_contents('http://www.test.com/');
preg_match('/<tr class="odd"><td ><b>Sunday</b> Info<div class="test">test<'/div><'/td><td>€ (.*) *<'/td><'/tr>/i', $data, $matches);
$result = $matches[1];
?>
但是没有结果...正则表达式中有什么问题?(我认为这是因为新的行/空格?
不要使用正则表达式,HTML 不是正则的。
相反,请使用像 DOMDocument
这样的 DOM 树解析器。这个documentation
可能会对你有所帮助。
/s
开关应该可以帮助您使用原始正则表达式,尽管我还没有尝试过。
问题是标签之间的空格。那里有换行符、制表符和/或空格。
您的正则表达式与它们不匹配。
您还需要为多行设置preg_match!
我认为使用 XPath 进行抓取更容易。
尝试用
"替换换行符,然后再次执行正则表达式。
尝试这样:
$uri = ('http://www.test.com/');
$get = file_get_contents($uri);
$pos1 = strpos($get, "<tr class='"odd'"><td ><b>Sunday</b> Info<div class='"test'">test</div></td><td>€");
$pos2 = strpos($get, "*</td></tr>", $pos1);
$text = substr($get,$pos1,$pos2-$pos1);
$text1 = strip_tags($text);
使用 PHP DOMDocument Object。我们将从网页解析HTML DOM数据
$dom = new DOMDocument();
$dom->loadHTML($data);
$trs = $dom->getElementsByTagName('tr'); // this gives us all the tr elements on the webpage
// loop through all the tr tags
foreach($trs as $tr) {
// until we get one with the class 'odd' and has a b tag value of SUNDAY
if ($tr->getAttribute('class') == 'odd' && $tr->getElementsByTagName('b')->item(0)->nodeValue == 'Sunday') {
// now set the price to the node value of the second td tag
$price = trim($tr->getElementsByTagName('td')->item(1)->nodeValue);
break;
}
}
而不是使用DOMDocument进行网络抓取,它有点乏味,你可以得到你的手SimpleHtmlDomParser,它是开源的。