致命错误:未捕获的 ValueError:DOMDocument::loadHTML():参数 #1 ($source) 不得为空

Fatal error: Uncaught ValueError: DOMDocument::loadHTML(): Argument #1 ($source) must not be empty

提问人:anpami 提问时间:7/22/2023 更新时间:7/22/2023 访问量:678

问:

我想使用 cURL 在 PHP 中抓取这个网站

我在PHP中使用类似的网络抓取脚本,它们运行良好。

但是,我收到以下错误:

Fatal error: Uncaught ValueError: DOMDocument::loadHTML(): Argument #1 ($source) must not be empty其次。Stack trace: #0 [...](29): DOMDocument->loadHTML() #1 {main} thrown in [...] on line 29

错误消息引用了第 29 行,即 (以下代码中的最后一行):$doc->loadHTML($html);

<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

$ch = curl_init();

// Set the cURL options
curl_setopt($ch, CURLOPT_URL, "https://link.springer.com/book/10.1007/978-3-031-10453-4");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');

// Execute the cURL request and fetch the HTML source code
$html = curl_exec($ch);

if (curl_error($ch)){
    $output = "\n". curl_error($ch);
    echo $output;
    die();
}

// Close the cURL handle
curl_close($ch);

// Create a new DOMDocument object
$doc = new DOMDocument();

// Load the HTML source code
$doc->loadHTML($html);

我不认为我被我想访问的网站阻止了 - 这是我第一次测试该网站。

错误背后的问题可能是什么?

php 网页抓取 curl domdocument

评论

0赞 Nigel Ren 7/22/2023
包含什么?(不是它应该包含什么,而是实际值)$html

答:

0赞 KIKO Software 7/22/2023 #1

这似乎是一个标头问题。我添加了一堆标题,它有效。我认为它特别需要一个 cookie 标头,但我不确定。这是我所做的:

$ch = curl_init();

$headers = ['Host: link.springer.com',
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0',
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
            'Accept-Language: en-US,en;q=0.5',
            'Accept-Encoding: gzip, deflate, br',
            'Alt-Used: link.springer.com',
            'Connection: keep-alive',
            'Cookie: sim-inst-token=""; trackid="zx2x19io4tsuk4vmfxbyuzwmw"; idp_session=sVERSION_14a94b0be-f404-438f-a28a-7fa100f381d4; idp_session_http=hVERSION_1982d3b5c-a7fc-4ee4-a0a5-5cbfbc9f57fc; idp_marker=4b716e5d-4a3f-4bc4-bf74-be595a696d13; user.uuid.v2="2577d0e2-af55-4b19-b21b-60267616d034"; sncc=P%3D17%3AV%3D35.0.0%26C%3DC01',
            'Upgrade-Insecure-Requests: 1',
            'If-None-Match: "9887e0016a5f403a529a66099f5cc49d"',
            'TE: trailers'];

// Set the cURL options
curl_setopt($ch, CURLOPT_URL, "https://link.springer.com/book/10.1007/978-3-031-10453-4");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Execute the cURL request and fetch the HTML source code
$html = curl_exec($ch);

需要进行更多调查才能准确了解需要哪些标头。

请注意,结果是压缩的,这就是为什么它看起来不像 HTML 的原因。