【问题标题】:PHP DOM Parsing URL did not return anythingPHP DOM 解析 URL 没有返回任何内容
【发布时间】:2019-05-16 19:39:30
【问题描述】:

我使用这个示例代码开始解析一个特殊的网站:

<?php

# Use the Curl extension to query Google and get back a page of results
$url = "http://www.google.com";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);
curl_close($ch);

# Create a DOM parser object
$dom = new DOMDocument();

# Parse the HTML from Google.
# The @ before the method call suppresses any warnings that
# loadHTML might throw because of invalid HTML in the page.
@$dom->loadHTML($html);

# Iterate over all the <a> tags
foreach($dom->getElementsByTagName('a') as $link) {
        # Show the <a href>
        echo $link->getAttribute('href');
        echo "<br />";
}
?>

Source

然后我将上面的 url 更改为 removed for privacy reasons 并再次运行脚本,但不,我没有输出,但使用 google-URL 它将工作。那么我的网站有什么问题呢?是避免解析的保护方法还是页面不符合标准?希望有人可以帮助我。

【问题讨论】:

  • 尝试输出 HTML 并查看它返回的内容。另请查看 HTTP 响应标头。话虽如此,如果 URL 在您的浏览器中而不是 curl 中有效,则很可能是因为它拒绝了未设置用户代理的请求。我以前见过几次。
  • 您的 curl 扩展是否启用?我可以使用您的代码检索链接

标签: php html parsing dom html-parsing


【解决方案1】:

看起来该站点仅返回 gzip 编码的响应。所以你需要设置正确的 cURL 编码并发送正确的编码头:

$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept-Encoding: gzip, deflate, br',
));
$html = curl_exec($ch);
curl_close($ch);

这对我有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 2016-06-23
    相关资源
    最近更新 更多