如何用PHP从MEPCO重复账单检查网站抓取数据?

问题描述 投票:0回答:2

我正在尝试使用 PHP 从 MEPCO bill site 抓取数据。具体来说,我想提取账单详细信息并将其保存到数据库中。

这是我想要从中抓取数据的 HTML 结构示例:

<html>
  <body>
    <div id="bill-details">
      <h2>Electricity Bill Details</h2>
      <p>Payable Amount: $200</p>
      <p>Due Date: 2023-05-01</p>
      <p>Description: This is your electricity bill for the month of April 2023.</p>
    </div>
  </body>
</html>

我想从此 HTML 中提取应付金额和到期日。这是我到目前为止尝试过的代码:

$html = '<html>...'; // the HTML from the example above
preg_match('/<h2>(.*)<\/h2>/', $html, $billHeading);
preg_match('/<p>Payable Amount: (.*)<\/p>/', $html, $payableAmount);
preg_match('/<p>Due Date: (.*)<\/p>/', $html, $dueDate);
echo "Bill Heading: ".$billHeading[1];
echo "Payable Amount: ".$payableAmount[1];
echo "Due Date: ".$dueDate[1];

但是,这段代码并没有按预期工作。它没有提取正确的应付金额和到期日。有人可以帮助我更正此代码或建议使用 PHP 从 HTML 中提取数据的更好方法吗?

php nsregularexpression
2个回答
0
投票

据我所知,你的例子似乎有效。这就是我跑的:

<?php

$html = <<<HTML
<html>
  <body>
    <div id="bill-details">
      <h2>Electricity Bill Details</h2>
      <p>Payable Amount: $200</p>
      <p>Due Date: 2023-05-01</p>
      <p>Description: This is your electricity bill for the month of April 2023.</p>
    </div>
  </body>
</html>
HTML;

preg_match('/<h2>(.*)<\/h2>/', $html, $billHeading);
preg_match('/<p>Payable Amount: (.*)<\/p>/', $html, $payableAmount);
preg_match('/<p>Due Date: (.*)<\/p>/', $html, $dueDate);
echo "Bill Heading: '".$billHeading[1] . "'\n";
echo "Payable Amount: '".$payableAmount[1] ."'\n";
echo "Due Date: '".$dueDate[1] ."'\n";

这就产生了这个结果:

Bill Heading: 'Electricity Bill Details'
Payable Amount: '$200'
Due Date: '2023-05-01'

如果不知道到底是什么不起作用,就很难说出问题是什么。至于改进方法,其他评论之一建议使用专门的 DOM 解析库,我同意这一点。如果您必须依赖正则表达式,我建议使模式尽可能具体。例如,如果日期始终是该格式,请使用类似

(\d{4}-\d{2}-\d{2})
的内容进行匹配。


-4
投票

我正在尝试使用 PHP 从 MEPCO 账单网站抓取数据。具体来说,我想提取账单详细信息并将其保存到数据库中。

感谢您提供此信息,我想问这个问题..

© www.soinside.com 2019 - 2024. All rights reserved.