【问题标题】:Fatal error: Uncaught Error: Call to a member function find() PHP simple_html_dom_parser [duplicate]致命错误:未捕获的错误:调用成员函数 find() PHP simple_html_dom_parser [重复]
【发布时间】:2023-03-27 16:06:01
【问题描述】:

我只想得到span的值

这是我的代码:

 <?php
        include('simple_html_dom.php');
        
        $html = file_get_html('https://ru.investing.com/commodities/gold');
        
        echo $html->find("span[class=arial_26 inlineblock pid-8830-last]",0)->plaintext;
        ?>

这是我的错误:

Fatal error: Uncaught Error: Call to a member function find() on bool in /home/f0514538/domains/f0514538.xsph.ru/public_html/test/crypto/tovar/gold.php:6 Stack trace: #0 {main} thrown in /home/f0514458/domains/f0514458.xsph.ru/public_html/test/crypto/tovar/gold.php on line 6
 

【问题讨论】:

    标签: php html parsing frameworks simple-html-dom


    【解决方案1】:

    $html 变量包含 boolean false 而不是您期望的 HTML 对象。您可以通过添加一个

    var_dump($html);
    

    $html 为空的原因是您尝试下载的网站有一些保护,不允许在没有有效用户代理的情况下下载。

    最简单的解决方法是手动设置您的用户代理,使用

    ini_set('user_agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36');
    

    所以整个代码就变成了

    include('simple_html_dom.php');
    ini_set('user_agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36');
    $html = file_get_html('https://ru.investing.com/commodities/gold');
    echo $html->find("span[class=arial_26 inlineblock pid-8830-last]", 0)->plaintext;
    

    请确保您没有在未经同意的情况下抓取内容而违反网站 T&C。

    【讨论】:

    • 谢谢兄弟,这是工作,我明白为什么会发生这个错误
    • 很高兴这有帮助。如果答案正确,请将其标记为正确答案,以帮助日后遇到类似问题的人快速找出正确的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2020-02-15
    • 2022-01-21
    • 2019-12-23
    • 1970-01-01
    相关资源
    最近更新 更多