php 爬虫 翻页,如果内容页有分页,该如何爬取到完整数据?

# 如果内容页有分页,该如何爬取到完整数据?

# 如果内容页有分页,该如何爬取到完整数据?

> 如果要爬取的某个内容页中有多个分页,该如何爬取这个内容页的完整数据呢?这里就无法使用`on_list_page`回调函数了,而需要使用`field`中的`attached_url`来请求其他分页的数据。

举个栗子:

爬取某网站文章时,发现有些文章有多个内容页面,处理过程如下:

```

$configs = array(

// configs 的其他成员

...

'fields' => array(

array(

'name' => "contents",

'selector' => "//div[@id='pages']//a//@href",

'repeated' => true,

'children' => array(

array(

// 抽取出其他分页的url待用

'name' => 'content_page_url',

'selector' => "//text()"

),

array(

// 抽取其他分页的内容

'name' => 'page_content',

// 发送 attached_url 请求获取其他的分页数据

// attached_url 使用了上面抓取的 content_page_url

'source_type' => 'attached_url',

'attached_url' => 'content_page_url',

'selector' => "//*[@id='big-pic']"

),

),

),

),

);

```

在爬取到所有的分页数据之后,可以在`on_extract_page`回调函数中将这些数据组合成完整的数据

```

$spider->on_extract_field = function($fieldname, $data, $page)

{

if ($fieldname == 'contents')

{

if (!empty($data))

{

$contents = $data;

$data = "";

foreach ($contents as $content)

{

$data .= $content['page_content'];

}

}

}

return $data;

};

```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值