【问题标题】:Website Scraping Using Regex trying to extract integers网站抓取使用正则表达式尝试提取整数
【发布时间】:2014-10-09 04:18:22
【问题描述】:

我无法从该网站提取括号内的整数。

来自网站的部分标记:

<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>' ;

}
?>

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

【问题讨论】:

标签: php xpath web web-scraping domdocument


【解决方案1】:

添加您当前的代码,这很简单,只需将 $class 更改为您想要的类并使用 -&gt;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);

【讨论】:

    【解决方案2】:
    <span[^>)()]*\((\d+)\)[^>]*>
    

    试试这个。抓住捕获。查看演示。

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

    【讨论】:

      猜你喜欢
      • 2016-01-28
      • 2011-12-02
      • 1970-01-01
      • 2014-07-03
      • 2020-09-28
      • 1970-01-01
      • 2017-02-02
      • 2014-07-18
      • 2022-11-17
      相关资源
      最近更新 更多