PHP简单爬虫CURL +Crawler 抓取取考研单词数据脚本

1 篇文章 0 订阅
1 篇文章 0 订阅

记录一个简单的爬虫功能,用来自己学习背诵单词。如果有侵权,立马删除。

目标是爬取一个网站的考研词汇。网址为:https://www.kuakao.com/english/ch/39243.html

首先在 在larvel框架中,生成一个artisan 脚本

 

我的代码:

 

 

填写数据:

 

开始写代码:

<?php

namespace App\Console\Commands;

use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Symfony\Component\DomCrawler\Crawler;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '抓取一下单词,这是临时脚本';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $client = new Client();
        //一共62个页面

        for ($number = 39184; $number < 39244; $number++) {
            try {
                $url = 'https://www.kuakao.com/english/ch/' . $number . '.html';
                $response = $client->request('GET', $url);
                //转为文本形式
                $body = $response->getBody()->getContents();
                //Crawler是一个 包,可以以选择器的形式来抓取 数据,比较方便。
                $crawler = new Crawler($body);
                //通过 class属性 加P标签,然后拿到每一个元素
                $english = $crawler->filter('.artTxt p')->each(function (Crawler $node, $i) {
                    return $node->text() . PHP_EOL;
                });
                //打印下看下效果
                dd($english);
                file_put_contents(base_path() . '/public/111.txt', $english);

            } catch (\Exception $e) {
                echo $number . '出错' . $e->getMessage() . $e->getLine();
                die;
                continue;
            }

        }

    }
}

运行结果:比较幸运,直接拿到了一个文件的。然后把它们放在一个TXT文件中。

 

然后整体运行,发现太慢了,也不知道执行到什么地方了,所以加个进度条吧。

最终代码:

 

<?php

namespace App\Console\Commands;

use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Symfony\Component\DomCrawler\Crawler;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '抓取一下单词,这是临时脚本';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $client = new Client();
        //一共62个页面
        $bar = $this->output->createProgressBar(62);
        $bar->start();
        for ($number = 39184; $number < 39244; $number++) {
            try {
                $url = 'https://www.kuakao.com/english/ch/' . $number . '.html';
                $response = $client->request('GET', $url);
                //转为文本形式
                $body = $response->getBody()->getContents();
                //Crawler是一个 包,可以以选择器的形式来抓取 数据,比较方便。
                $crawler = new Crawler($body);
                //通过 class属性 加P标签,然后拿到每一个元素
                $english = $crawler->filter('.artTxt p')->each(function (Crawler $node, $i) {
                    return $node->text() . PHP_EOL;
                });
                //打印下看下效果
                foreach($english as $oneWord){
                    file_put_contents(base_path() . '/public/englishNote.txt', $oneWord.'\n',FILE_APPEND);
                }

            } catch (\Exception $e) {
                echo $number . '出错' . $e->getMessage() . $e->getLine();
                die;
                continue;
            }
            $bar->advance();

        }
        $bar->finish();
        echo '恭喜全部完成';die;

    }
}

 

看下效果吧:

看来\n,我加的多余了,让各位大神耻笑了,我会继续加油。有什么问题欢迎大家留言。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用PHPcurl库可以方便地实现网页抓取功能。通过curl库,我们可以发送HTTP请求并获服务器响应的内容。以下是一个使用php curl抓取页面所有链接的方法: 1. 创建一个curl资源句柄: ``` $ch = curl_init(); ``` 2. 设置curl选项,包括目标URL、请求头信息和其他参数: ``` curl_setopt($ch, CURLOPT_URL, "目标URL"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4"); ``` 其中,`CURLOPT_URL`用于设置目标URL,`CURLOPT_RETURNTRANSFER`用于设置是否将抓取的内容作为字符串返回,`CURLOPT_FOLLOWLOCATION`用于设置是否跟随重定向,`CURLOPT_USERAGENT`用于设置用户代理。 3. 执行curl请求并获响应内容: ``` $response = curl_exec($ch); ``` 4. 使用正则表达式或其他方法从响应内容中提所有链接: ``` preg_match_all('/<a\s+href=["\'](.*?)["\']/', $response, $matches); $links = $matches<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [php curl抓取网页的介绍和推广及使用CURL抓取淘宝页面集成方法](https://download.csdn.net/download/weixin_38594687/13020038)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [PHP curl实现抓取302跳转后页面的示例](https://download.csdn.net/download/weixin_38500572/13045232)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [phpcurl抓取页面](https://blog.csdn.net/weixin_27727467/article/details/115831006)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值