网站刮痧使用正则表达式等

时间:2014-10-09 04:18:22

标签: php xpath web web-scraping domdocument

我无法从本网站的括号中提取整数。

网站标记的一部分:

<span class="b-label b-link-number" data-num="(322206)">Music &amp; Video</span>
<span class="b-label b-link-number" data-num="(954218)">Toys, Hobbies &amp; Games</span>
<span class="b-label b-link-number" data-num="(502981)">Kids, Baby &amp; Maternity</span>

如何提取括号之间的整数?

期望的输出:

322206
954218
502981

我应该使用正则表达式,因为它们具有相同的类名(但不是正则表达式,因为括号内的其他不需要的元素也来自源代码)。

通常,这将是我用来提取信息的方式:

<?php
//header('Content-Type: text/html; charset=utf-8');
$grep = new DoMDocument();
@$grep->loadHTMLFile("http://global.rakuten.com/en/search/?tl=&k=");
$finder = new DomXPath($grep);
$class = "b-list-item";
$nodes = $finder->query("//*[contains(@class, '$class')]");

foreach ($nodes as $node) {
    $span = $node->childNodes;
    $search = array(0,1,2,3,4,5,6,7,8,9,'(',')');
    $categories = str_replace($search, '', $span->item(0)->nodeValue);
    echo '<br>' . '<font color="green">' . $categories . '  ' . '</font>' ;

}
?>

但由于我想要的数据在标签内部,我该如何提取它们?

2 个答案:

答案 0 :(得分:2)

添加您当前的代码,简单直接,只需将$class更改为您想要的类,并使用->getAttribute()来获取data-num

$grep = new DoMDocument();
@$grep->loadHTMLFile("http://global.rakuten.com/en/search/?tl=&k=");
$finder = new DomXPath($grep);
$class = "b-link-number"; // change the span class
$nodes = $finder->query("//*[contains(@class, '$class')]"); // target those

$numbers = array();
foreach ($nodes as $node) { // for every found elemenet
    $link_num = $node->getAttribute('data-num'); // get the attribute `data-num`
    $link_num = str_replace(['(', ')'], '', $link_num); // simply remove those parenthesis
    $numbers[] = $link_num; // push it inside the container
}

echo '<pre>';
print_r($numbers);

答案 1 :(得分:1)

<span[^>)()]*\((\d+)\)[^>]*>

试试这个。抓住捕获。参见演示。

http://regex101.com/r/iM2wF9/10