【问题标题】:Fatal error: Uncaught Error: Call to a member function find() on null using Simple HTML DOM致命错误:未捕获的错误:使用简单 HTML DOM 在 null 上调用成员函数 find()
【发布时间】:2016-10-20 04:17:02
【问题描述】:

我正在使用 Simple HTML DOM 从我正在抓取的网站中获取元素和值。它工作得很好,但是每 23,000 页左右,我就会遇到一个 404 页面未找到的页面,其中不存在正常的 html 结构。这会导致我想在不破坏页面的情况下转义的致命错误。

这是完整的错误报告:

致命错误: 未捕获的错误:在 C:\xampp\htdocs\scrape\simple_html_dom.php:1113 中调用成员函数 find() 的 null 堆栈跟踪:#0 C:\xampp \htdocs\scrape\scrape_detailtable.php(133): simple_html_dom->find('div[id=detailta...') #1 {main} 在 C:\xampp\htdocs\scrape\simple_html_dom.php 中抛出上线1113

以下是我的脚本中发生错误的行:

$doc = new simple_html_dom($record_content);
if ( ! is_null($doc->find("div[id=detailtable]")) ) // <-- this line

$record_content 是使用 cURL 检索到的 html。

我试过了

if( ! isset($doc->find("div[id=detailtable]")) ) , 
if( ! is_null($doc->find("div[id=detailtable]")) ) , 
if( ! empty($doc->find("div[id=detailtable]")) ) , and , 
if( ! $doc->find("div[id=detailtable]") )  ...

...页面不断中断。我只想在 div[id=detailtable] 存在的情况下逃避处理。

2016 年 6 月 30 日更新

我在尝试不同的转义和“检测非空”方法时遇到另一个 PHP 错误(也许这是 PHP 7 的新功能)。最终,我尝试了一些 PHP 抛出此建议的方法,以及错误:(释义)“您可以使用 null !== 表达式”

所以现在我的代码是:if ( null !== $doc-&gt;find( 'a' ) ){

废话!仍然收到“未捕获的错误:在 null 上调用成员函数 find()”所以我猜 null !== 表达式并没有真正起作用。

【问题讨论】:

  • 你可以试试if ( ! is_null($doc-&gt;find("div[id=detailtable]", 0)) ) 代替if ( ! is_null($doc-&gt;find("div[id=detailtable]")) ) 吗?不确定这个但值得一试:)
  • 似乎$doc 为空(因为它是您调用find() 的那个变量)。尝试调试代码,看看会发生什么。 new simple_html_dom(..) 调用不应创建 null 对象,这有点奇怪。这是错误的确切代码吗?
  • @InfiniteLoop 好酷,很高兴它有帮助!祝你好运!
  • 对 simple_html_dom 代码的仔细检查表明 find 方法调用了内部 $this-&gt;root-&gt;find(..) 方法,根可能为空,这就是它爆炸的原因。你说它是重定向,simple_html_dom 是否跟随重定向?
  • @Jite,它不遵循重定向。因此,我认为这就是根为空的方式。它点击一个没有 id="detailtable" 的页面,我得到一个空值。所以,我认为你的分析是正确的。我实际上需要在 null 上转义。现在,脚本正在运行,没有错误。

标签: php web-scraping simple-html-dom


【解决方案1】:

试试这样的:

$doc = new simple_html_dom($record_content);
if ( $doc ) {
    if ( ($find = $doc->find("div[id=detailtable]")) ) {
        // do what you want with the $find variable
    }
    if ( ($find = $doc->find("div[id=detailtable2]")) ) {
        // do what you want with the $find variable
    }
    if ( ($find = $doc->find("div[id=detailtable3]")) ) {
        // do what you want with the $find variable
    }
} 

【讨论】:

  • 有了这个,我已经从剖析html中知道只有一个div[id=detailtable]。从来没有div[id=detailtable2]div[id=detailtable3]。当没有div[id=detailtable] 时,它会触发我试图摆脱的错误。这样就只剩下内部的if。但是我已经尝试过if ( ($find = $doc-&gt;find("div[id=detailtable]")) ) {,它并不能阻止页面因错误而中断。谢谢。
  • @InfiniteLoop detailtable2detailtable3.... 只是举例 ;-) 如果我的回答回答了您的问题,请单击按钮选择我的回答作为正确答案 :)
  • 感谢@keupsonite 的回答。我很感激。但恐怕你的回答并不能真正阻止错误的发生。我知道,我试过了。
  • @InfiniteLoop 错误还是和以前一样?!如果没有,能不能把错误信息放上去?
猜你喜欢
  • 2020-10-04
  • 2016-04-20
  • 2020-08-24
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2018-10-11
  • 2017-07-13
  • 2021-12-18
相关资源
最近更新 更多