Home Backend Development PHP Tutorial PHP crawler practice: crawling MOOC course information

PHP crawler practice: crawling MOOC course information

Jun 13, 2023 am 11:35 AM
php reptile course information

With the development of the Internet, crawler technology has played an increasingly important role in modern data collection, data analysis and business decision-making. Learning how to use crawler technology will greatly improve the efficiency and accuracy of our data processing. In this article, we will use PHP to write a crawler to crawl course information on MOOC.

The tools that will be used in this article are as follows:

  • PHP programming language, version is PHP 7.0
  • Third-party library Guzzle HTTP Client, used to send HTTP requests and receive HTTP response
  • A simple MySQL database used to store the course information we captured

1. Preparation work

First, we need to create a local environment Install PHP 7.0 version, the installation process is omitted.

Guzzle HTTP Client is a commonly used HTTP client tool library, we can use Composer to install it. Switch to a blank directory on the command line, then create a new composer.json file and add the following content:

{

"require": {
    "guzzlehttp/guzzle": "^6.3"
}
Copy after login

}

Then at the same level Execute composer install in the directory. After the execution is completed, we have successfully installed Guzzle HTTP Client.

2. Analyze the structure of the target website

Before we start writing code, we need to analyze the structure of the target website. We chose the Python course on MOOC.com (www.imooc.com). The information we need to capture includes course name, course number, course difficulty, course duration and course link.

After opening the target website and performing certain operations (such as searching for "Python" courses), we can view the response content returned by the website. We can use the browser's development tools to view the response content and web page structure.

We can see that the list of Python courses on MOOC is dynamically loaded through AJAX. In order to facilitate data crawling, we can directly look up the URL and parameters of the AJAX request, and then construct our own HTTP request to obtain the data.

By looking at the XHR request of the target website, we can find that the actual requested URL for the Python course is http://www.imooc.com/course/AjaxCourseMore?&page=1.

The page in the request parameter indicates the page number currently to be accessed. We can send a request to the URL through the HTTP GET method and parse it based on the returned results.

3. Write a crawler program

In the previous step we have obtained the list URL of the Python course of the target website. Now we only need to write PHP code, use Guzzle HTTP Client to send HTTP requests, and then parse Just return the result.

First, we need to introduce the Guzzle HTTP Client library. Add the following code at the top of the PHP file:

require 'vendor/autoload.php';

Then create a Guzzle HTTP Client object:

$client = new GuzzleHttpClient( );

Next, we can use this object to send an HTTP request:

$response = $client->request('GET', 'http://www.imooc.com /course/AjaxCourseMore?&page=1');

In the above code, we use the request() method of the Guzzle HTTP Client object, specifying that the request method is GET, and the requested URL is what we specified in the previous step The URL obtained.

Finally, we need to get the course information we need from the HTTP response. By inspecting the response content, we can see that the course information is contained in an HTML tag with the class attribute of course-card-container.

We can use PHP's DOMDocument class to traverse HTML tags and parse out the tags that meet the conditions.

The final code implementation is as follows:

require 'vendor/autoload.php';

use GuzzleHttpClient;

$client = new Client([

'base_uri' => 'http://www.imooc.com'
Copy after login
Copy after login

]);

$response = $client->request('GET', '/course/AjaxCourseMore?&page=1');

if ($ response->getStatusCode() == 200) {

$dom = new DOMDocument();
@$dom->loadHTML($response->getBody());

$xpath = new DOMXPath($dom);

$items = $xpath->query("//div[@class='course-card-container']");

foreach ($items as $item) {
    $courseName = trim($xpath->query(".//h3[@class='course-card-name']/a", $item)->item(0)->textContent);
    $courseId = trim($xpath->query(".//div[@class='clearfix']/a[@class='course-card'], $item)->item(0)->getAttribute('href'));
    $courseDifficulty = trim($xpath->query(".//p[@class='course-card-desc']", $item)->item(0)->textContent);
    $courseDuration = trim($xpath->query(".//div[@class='course-card-info']/span[@class='course-card-time']", $item)->item(0)->textContent);
    $courseLink = trim($xpath->query(".//h3[@class='course-card-name']/a", $item)->item(0)->getAttribute('href'));

    // 将抓取到的数据存储到MySQL数据库中
    // ...

    echo "课程名称:" . $courseName . "
Copy after login

";

    echo "课程编号:" . $courseId . "
Copy after login

";

    echo "课程难度:" . $courseDifficulty . "
Copy after login

";

    echo "课程时长:" . $courseDuration . "
Copy after login

";

    echo "课程链接:" . $courseLink . "
Copy after login

";

}
Copy after login

}

We use DOMDocument to read the HTML response content, and then use DOMXPath to traverse the tags. Finally, we print the captured information to the screen.

4. Store data

Now we have successfully captured the information of the Python course and printed the information to the screen. However, it is not practical to print the data to the screen. We The data needs to be saved to the database.

In the MySQL database, we created a table to store information about Python courses. The table structure is as follows:

CREATE TABLE python_courses (
id int(11) unsigned NOT NULL AUTO_INCREMENT,
course_name varchar(255) NOT NULL DEFAULT '',
course_id varchar(255) NOT NULL DEFAULT '',
course_difficulty varchar(255) NOT NULL DEFAULT '',
course_duration varchar(255) NOT NULL DEFAULT '',
course_link varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

In the code, we use PDO to connect to the MySQL database, and use the prepare() method and execute() method to perform the insertion operation. The final code is as follows:

require 'vendor/autoload.php';

use GuzzleHttpClient;

$client = new Client([

'base_uri' => 'http://www.imooc.com'
Copy after login
Copy after login

] );

$response = $client->request('GET', '/course/AjaxCourseMore?&page=1');

if ($response->getStatusCode() == 200) {

$dom = new DOMDocument();
@$dom->loadHTML($response->getBody());

$xpath = new DOMXPath($dom);

$items = $xpath->query("//div[@class='course-card-container']");

$dsn = 'mysql:host=localhost;dbname=test';
$username = 'root';
$password = '';
$pdo = new PDO($dsn, $username, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

$stmt = $pdo->prepare("INSERT INTO `python_courses` (`course_name`, `course_id`, `course_difficulty`, `course_duration`, `course_link`) VALUES (:course_name, :course_id, :course_difficulty, :course_duration, :course_link)");
foreach ($items as $item) {
    $courseName = trim($xpath->query(".//h3[@class='course-card-name']/a", $item)->item(0)->textContent);
    $courseId = trim($xpath->query(".//div[@class='clearfix']/a[@class='course-card']", $item)->item(0)->getAttribute('href'));
    $courseDifficulty = trim($xpath->query(".//p[@class='course-card-desc']", $item)->item(0)->textContent);
    $courseDuration = trim($xpath->query(".//div[@class='course-card-info']/span[@class='course-card-time']", $item)->item(0)->textContent);
    $courseLink = trim($xpath->query(".//h3[@class='course-card-name']/a", $item)->item(0)->getAttribute('href'));

    $stmt->bindParam(':course_name', $courseName);
    $stmt->bindParam(':course_id', $courseId);
    $stmt->bindParam(':course_difficulty', $courseDifficulty);
    $stmt->bindParam(':course_duration', $courseDuration);
    $stmt->bindParam(':course_link', $courseLink);
    $stmt->execute();
}
Copy after login

}

现在,我们已经成功的构建了一个简单的PHP爬虫,用于抓取慕课网上的Python课程信息。经过这个例子的介绍,你应该可以使用PHP编写你自己的爬虫程序,并获取到你需要的数据了。

The above is the detailed content of PHP crawler practice: crawling MOOC course information. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

See all articles