首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从多个链接中抓取数据

从多个链接中抓取数据
EN

Stack Overflow用户
提问于 2014-08-29 01:14:59
回答 1查看 582关注 0票数 1

我有一个PHP代码,它将从"level0 nav-1活动父级“的类名中检索数据。有没有一种方法,我可以提供一个链接数组,并使用一个稍微不同的类名,为每个循环的链接数组,而不必重复相同的代码,为类似10个链接?

类似于:第一链接(https://www.postme.com.my/men-1.html)-使用类("level0 nav-1活动父“)第二(https://www.postme.com.my/women.html)-使用类("level0 nav-2活动父”)第三(https://www.postme.com.my/children.html)-使用类("level0 nav-3活动父“)

注意到递增的导航#了吗?

这是php代码:

代码语言:javascript
复制
<?php
header('Content-Type: text/html; charset=utf-8');
$grep = new DoMDocument();
@$grep->loadHTMLFile("https://www.postme.com.my/men-1.html");

$finder = new DomXPath($grep);
$classCat = "level0 nav-1 active parent";

$nodesCat = $finder->query("//*[contains(@class, '$classCat')]");

$i = 0;

    foreach ($nodesCat as $node) {
    $span = $node->childNodes;
    $replace = str_replace("Items 1-12 of", "",$span->item(1)->nodeValue);

    echo $replace. " : ";
  }

  // Check another link using class name of "level0 nav-2 active parent"
  //repeat code 

  @$grep->loadHTMLFile("https://www.postme.com.my/women.html");

$finder = new DomXPath($grep);
$classCat = "level0 nav-2 active parent";

$nodesCat = $finder->query("//*[contains(@class, '$classCat')]");

$i = 0;

    foreach ($nodesCat as $node) {
    $span = $node->childNodes;
    $replace = $span->item(1)->nodeValue;

    echo $replace. " : ";
  }
//check another link with class name "level0 nav-3 active parent".
//notice the incrementing nav-#?
//I don't want to make the code long just because each link is using a slightly different class name to refer to the data.
?>

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-29 01:40:24

我要做的是获取这些链接(<li>)的父级,即<ul id="nav">。然后从那里开始。提取值。示例:

代码语言:javascript
复制
$dom = new DOMDocument();
@$dom->loadHTMLFile('https://www.postme.com.my/men-1.html');
$xpath = new DOMXpath($dom);

$categories = $xpath->query('//ul[@id="nav"]/li');

foreach($categories as $category) {
    echo $xpath->query('./a/span', $category)->item(0)->nodeValue . '<br/>';
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25560280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档