gpt4 book ai didi

php - 使用正则表达式尝试提取整数的网站抓取

转载 作者:行者123 更新时间:2023-12-01 23:54:07 25 4
gpt4 key购买 nike

我无法从此网站提取括号之间的整数。

网站的部分标记:

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

}
?>

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

最佳答案

添加当前代码,非常简单,只需将 $class 更改为您想要的类,然后使用 ->getAttribute() 获取这些 >数据编号的:

$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);

关于php - 使用正则表达式尝试提取整数的网站抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26270256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com