Các trang web được thu thập thông tin không chèn vào bảng SQL của tôi | Trình thu thập dữ liệu web PHP

lập trình


Tôi đã tạo một trình thu thập dữ liệu web PHP và sau đó tạo một bảng MySQL có tên là “dex” làm chỉ mục, sau đó tôi kết nối với cơ sở dữ liệu thông qua PDO và điều chỉnh mã thành các trang web “INSERT” chưa được thu thập dữ liệu vào bảng, ” CẬP NHẬT” dành cho các trang web được thu thập thông tin và sử dụng hàm băm URL làm chỉ báo hoặc “id” cho các liên kết. Terminal hiển thị tất cả các link và liên kết liên quan đến chúng, câu lệnh if hoạt động hoàn hảo và không có lỗi gì lớn, vậy tại sao nó không chèn dữ liệu vào bảng “dex”? mỗi lần tôi kiểm tra bảng sau quá trình, tôi chỉ tìm thấy hàng mà tôi đã chèn theo cách thủ công để kiểm tra câu lệnh if cho “CẬP NHẬT” hoặc “CHÈN”. Tôi có thể làm gì để khắc phục sự cố này và chèn ngày truy xuất của trình thu thập thông tin?

Kiểm tra.html:

<a href="https://google.com"></a>
<a href="https://www.yahoo.com/"></a>
<a href="https://www.bing.com/"></a>
<a href="https://duckduckgo.com/"></a>

Trình thu thập thông tin:

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

$start = "http://localhost/deepsearch/test.html";

$pdo = new PDO('mysql:host=127.0.0.1;dbname=deepsearch', 'root', '');

$already_crawled = array();
$crawling = array();

function get_details($url) {
    $options = array('http'=>array('method'=>"GET", 'headers'=>"User-Agent: howBot/0.1\n"));
    $context = stream_context_create($options);

    // Suppress warnings for HTML parsing errors
    libxml_use_internal_errors(true);

    $doc = new DOMDocument();
    @$html = @file_get_contents($url, false, $context);

    // Load HTML content and check for parsing errors
    if ($doc->loadHTML($html)) {
        if (!empty($titleElements)) {
            $title = $titleElements->item(0);
            $title = $title->nodeValue;
        } else {
            $title = "";
        }
        
        $description = "";
        $keywords = "";
        $metas = $doc->getElementsByTagName("meta");
        for ($i = 0; $i < $metas->length; $i++) {
            $meta = $metas->item($i);

            if ($meta->getAttribute("name") == strtolower("description")) {
                $description = $meta->getAttribute("content");
            }
            if ($meta->getAttribute("name") == strtolower("keywords")) {
                $keywords = $meta->getAttribute("content");
            }
        }

        return '{"Title": "'.str_replace("\n", "", $title).'", "Description": "'.str_replace("\n", "", $description).'", "Keywords": "'.str_replace("\n", "", $keywords).'", "URL": "'.$url.'"}';
    } else {
        // Handle the parsing error
        echo "HTML parsing error: " . libxml_get_last_error()->message . "\n";
        return ''; // Return an empty string or handle the error as needed
    }
}
function follow_links($url)
{

    global $pdo;
    global $already_crawled;
    global $crawling;

    $options = array('http' => array('method' => "GET", 'headers' => "User-Agent: howBot/0.1\n"));
    $context = stream_context_create($options);

    $doc = new DOMDocument();
    @$doc->loadHTML(@file_get_contents($url, false, $context));

    $linklist = $doc->getElementsByTagName("a");

    foreach ($linklist as $link) {
        $l = $link->getAttribute("href");

        if (substr($l, 0, 1) == "/" && substr($l, 0, 2) != "//") {
            $l = parse_url($url)["scheme"] . "://" . parse_url($url)["host"] . $l;
        } else if (substr($l, 0, 2) == "//") {
            $l = parse_url($url)["scheme"] . ":" . $l;
        } else if (substr($l, 0, 2) == "./") {
            $l = parse_url($url)["scheme"] . "://" . parse_url($url)["host"] . dirname(parse_url($url)["path"]) . substr($l, 1);
        } else if (substr($l, 0, 1) == "#") {
            $l = parse_url($url)["scheme"] . "://" . parse_url($url)["host"] . parse_url($url)["path"] . $l;
        } else if (substr($l, 0, 3) == "../") {
            $l = parse_url($url)["scheme"] . "://" . parse_url($url)["host"] . "/" . $l;
        } else if (substr($l, 0, 11) == "javascript:") {
            continue;
        } else if (substr($l, 0, 5) != "https" && substr($l, 0, 4) != "http") {
            $l = parse_url($url)["scheme"] . "://" . parse_url($url)["host"] . "/" . $l;
        }

        if (!in_array($l, $already_crawled)) {
            $already_crawled[] = $l;
            $crawling[] = $l;

            $details = json_decode(get_details($l));
            echo $details->URL . " ";

            $rows = $pdo->query("SELECT * FROM dex WHERE url_hash='" . md5($details->URL) . "'");
            $rows = $rows->fetchColumn();

            $params = array(':title' => $details->Title, ':description' => $details->Description, ':keywords' => $details->Keywords, ':url' => $details->URL, ':url_hash' => md5($details->URL));

            if ($rows > 0) {
                echo "UPDATE" . "\n";
            } else {

                if (!is_null($params[':title']) && !is_null($params[':description']) && $params[':title'] != '') {

                    $result = $pdo->prepare("INSERT INTO dex (title, description, keywords, url, url_hash) VALUES (:title, :description, :keywords, :url, :url_hash)");
                    $result= $result->execute($params); 


                    //if ($result) {
                    //    echo "Inserted successfully.\n";
                    //} else {
                    //    echo "Insertion failed.\n";
                    //    print_r($stmt->errorInfo());
                    //}
                }
            }


            //print_r($details)."\n";
            //echo get_details($l)."\n";
            //echo $l."\n";
        }

    }
    array_shift($crawling);
    foreach ($crawling as $site) {
        follow_links($site);
    }
}




follow_links($start);
//print_r($already_crawled);
?>

Những gì tôi đã thử:

lúc đầu, tôi đã thử các liên kết khác nhau nhưng nhận được một giá trị trống, dẫn đến lỗi và cảnh báo, sau đó tôi thay đổi các liên kết và bắt đầu viết câu lệnh “UPDATE”, “INSERT” if và bắt đầu viết cụ thể chèn PDO trước để kiểm tra nó. Khi tôi thực thi tệp bằng lệnh php, tôi đã nhận được kết quả mong muốn về cách nó trông như thế nào trong thiết bị đầu cuối nhưng sau đó tôi kiểm tra trên bảng và phát hiện ra rằng không có gì được chèn vào. Tôi muốn chèn chúng để sử dụng chúng trong công cụ tìm kiếm của mình và làm cho chúng có thể tìm kiếm được bằng truy vấn.

Giải pháp 1

Thay vì phát triển mọi thứ từ đầu, tại sao bạn không sử dụng trình phân tích cú pháp hiện có như Tài liệu DOM HTML đơn giản[^] ?

Cái này hoạt động rất tốt và sẽ giúp bạn tiết kiệm hàng giờ phát triển. Phần còn lại thật dễ dàng – hàng đợi các liên kết để xử lý, v.v. Tôi cũng chia trình thu thập thông tin và trình phân tích cú pháp thành hai tập lệnh riêng biệt – một tập lệnh để thu thập thông tin và tập lệnh thứ hai để phân tích cú pháp và trích xuất URL.

コメント

タイトルとURLをコピーしました