我正在编写一个 php,其中功能之一是通过 Puppeteer 从互联网上抓取数据。感谢 ggorlen 的帮助,我的 js 工作正常。现在,我想在我的 php 中运行 node.js。我在网上搜索并尝试模仿一些例子,但失败了。这是我的 php(Bulletin Translator.php):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>contacts.php</title>
</head>
<body text="blue">
<?php
exec('cd js');
exec('node index.js');
?>
<?php
// Some php code here.
?>
</body>
</html>
index.js:
const puppeteer = require('puppeteer');
//var date_in_YMD = new Date();
(async ()=>
{
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(weather_report_chin_html)
// let's just call them tweetHandle
//const bulletin_urls = await page.$$('div.leftBody > ul[class^="list"]');
const bulletin_urls = await page.$$('div.leftBody');
// loop thru all handles
for(const bulletin_url of bulletin_urls)
{
try
{
const data = await page.$$eval(".NEW", els => els.map(el => (
{
text: el.textContent,
href: el.href,
})));
console.log(data);
}
catch(err)
{
console.error(err);
}
}
await browser.close()
}) ();
我应该怎么做才能在我的 php 中运行 node.js?我该如何将抓取结果导入到我的 php 中?任何建议将不胜感激。
为此,您根本不需要 Puppeteer。如果您使用 PHP,请直接使用它而不是 Node。使用 PHP 将变得更快、更容易编码并且在各个方面都更易于维护:
<?php
use DiDom\Document;
require_once("vendor/autoload.php");
$url = "<Your URL>";
$html = file_get_contents($url);
if ($html === false) {
throw new Exception("Failed to fetch URL");
}
$document = new Document($html);
$data = [];
foreach ($document->find(".NEW") as $element) {
$text = $element->text();
$href = $element->getAttribute("href");
$data[] = ["text" => $text, "href" => $href];
}
echo json_encode($data, JSON_PRETTY_PRINT) . "\n";
echo count($data) . "\n";
?>
我使用以下答案在 Ubuntu 22.04 上实现了此功能: