IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> PHP知识库 -> PHP 抓取网站内容 -> 正文阅读

[PHP知识库]PHP 抓取网站内容

这里以guzzle方式为例,curl类似

用guzzle需要先安装guzzle依赖,安装方式直接用composer就行,这里就不在过多阐述

安装完guzzle后,以下代码是简单的guzzle的使用

一、直接请求

$client = new \GuzzleHttp\Client();
$response = new \GuzzleHttp\Psr7\Request('GET', "https://m.baidu.com");
// 获取头部信息
$header = $response->getHeaders();
// 获取html
$body = $response->getBody();
//        echo $body;
// 转换为字符串
$stringBody = (string) $body;

//对结果过滤,取出class='title'的p标签内容,结果为数组格式的结果集
$tag = 'p';
$attr = 'class';
$value = 'title';
$html = $stringBody;
$regex = "/<$tag.*?$attr=\".*?$value.*?\".*?>(.*?)<\/$tag>/is";
preg_match_all($regex,$html,$matches,PREG_PATTERN_ORDER);
var_dump($matches[1]);

// 从body中读取10字节
$tenBytes = $body->read(10);

二、同时并发抓取

<?php
namespace App\Console\Commands;
use App\Libs\mCache;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Pool;
use Illuminate\Console\Command;
use DB;
use function GuzzleHttp\Psr7\str;

//use App\Models\ArticleModel;
//use App\Models\ArticleCateModel;

class Spider extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'Spider';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Spider';
    private $totalPageCount;
    private $counter        = 1;
    private $concurrency    = 2;  // 同时并发抓取

    private $users = 1;

//    protected $signature = 'test:multithreading-request';
//    protected $description = 'Command description';

    public function __construct()
    {
        parent::__construct();
    }
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->totalPageCount = $this->users;

        $client = new Client();

        $requests = function ($total) use ($client) {
            for ($i=1;$i<=$this->users;$i++){
                $uri = "https://m.xxx.net/xclass/0/{$i}.html";
                yield function() use ($client, $uri) {
                    return $client->getAsync($uri);
                };
            }
//            foreach ($this->users as $key => $user) {
//
//                $uri = 'https://www.xxx.net/xclass/1/1.html';
//                yield function() use ($client, $uri) {
//                    return $client->getAsync($uri);
//                };
//            }
        };

        $pool = new Pool($client, $requests($this->totalPageCount), [
            'concurrency' => $this->concurrency,
            'fulfilled'   => function ($response, $index){

                $res = (string)$response->getBody();
                $book = getLabel($res,"div","class","booklist");
                foreach ($book as $val){
                    $img = getLabel($val,"img","","");
                    echo $img[0];
                    $title = getLabel($val,"p","class","title");
                    echo $title[0];
                    $author = getLabel($val,"p","class","author");
                    echo $author[0];
//                    $book_id = mCache::getBookId($title[0]);
//                    var_dump($book_id);
//                    DB::transaction(function () {
//                        $res = DB::table('book')->get();
//                        var_dump($res);
                        DB::table('book')->update(['votes' => 1]);

                        DB::table('posts')->delete();
//                    });
                }

                $this->info("请求第 $index 页数据");

                $this->countedAndCheckEnded();
            },
            'rejected' => function ($reason, $index){
                $this->error("rejected" );
                $this->error("rejected reason: " . $reason );
                $this->countedAndCheckEnded();
            },
        ]);

        // 开始发送请求
        $promise = $pool->promise();
        $promise->wait();
    }
    public function countedAndCheckEnded()
    {
        if ($this->counter < $this->totalPageCount){
            $this->counter++;
            return;
        }
        $this->info("请求结束!");
    }
}
function getLable($html,$tag,$attr,$value){
    $regex = "/<$tag.*?$attr=\".*?$value.*?\".*?>(.*?)<\/$tag>/is";
    if($tag == 'src'){
        $regex = '/<img.*?src="(.*?)".*?>/is';    
    }
    preg_match_all($regex,$html,$matches,PREG_PATTERN_ORDER);
    return $matches[1];
}

?

guzzle的功能很强大,具体的的可自己看文档

  PHP知识库 最新文章
Laravel 下实现 Google 2fa 验证
UUCTF WP
DASCTF10月 web
XAMPP任意命令执行提升权限漏洞(CVE-2020-
[GYCTF2020]Easyphp
iwebsec靶场 代码执行关卡通关笔记
多个线程同步执行,多个线程依次执行,多个
php 没事记录下常用方法 (TP5.1)
php之jwt
2021-09-18
上一篇文章      下一篇文章      查看所有文章
加:2021-08-07 11:46:44  更:2021-08-07 11:47:17 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年4日历 -2024/4/28 7:09:39-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码