gpt4 book ai didi

带有特定标记的 PHP DOM html 问题

转载 作者:搜寻专家 更新时间:2023-10-31 21:21:08 25 4
gpt4 key购买 nike

人。我通常会在网上和 stackoverflow 上找到我的答案,但这次无法解决我的问题。我正在使用 php dom 来解析网站并从中提取一些数据,但出于某种原因,我尝试的所有方法总是返回给我的项目少于页面上的数量。

尝试了“simple php simple html dom”、“php advanced html dom”和原生 php dom...但在这种情况下,仍然得到 14 个文章标签。

http://www.emol.com/movil/nacional/

在这个站点中有 28 个标记为“文章”的元素,但我总是得到 14 个(或更少)

尝试使用经典的查找(从简单和高级),所有可能的组合;并使用 native 查询 xpath 和 getelementsbytag。

$xpath->query('//article');
$xpath->query('//*[@id="listNews"]/article[6]') //even this don't work
$html->find('article:not(.sec_mas_vistas_emol), article'); //return 14

所以我的猜测是我加载 url 的方式...所以我尝试了经典的“file_get_html”、curl 和一些自定义函数...它们都是相同的。更奇怪的是,如果我使用在线 xpath 测试器,复制所有 html 并使用“query->('//article')...它找到所有。这是我最后的两个测试:

//Way 1
$html = file_get_html('http://www.emol.com/movil/nacional/');
$lidata = $html->find('article');

//Way 2
$url = 'http://www.emol.com/movil/nacional';
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$e = curl_exect($ch);
$dom = new DOMDocument;
@$dom->loadHTML($e); //tryed with loadHTMLFile too and the libxml_use_internal_erros
$xpath = new DOMXPath($dom);
$xpath->query('//article');

关于可能是什么问题以及解决问题的方法有什么建议吗?实际上,这是我第一次接触 PHP dom,所以可能我遗漏了什么。

最佳答案

也许我上面的评论和这个例子可以帮助你继续。

使用 phpcasperjs 包装器:

<?php 

require_once 'vendor/autoload.php';

use Browser\Casper;

$casper = new Casper();
$casper->start('http://www.emol.com/movil/nacional/');
$casper->wait(5000);
$output = $casper->getOutput();
$casper->run();
$html = $casper->getHtml();
$dom = new DOMDocument('1.0', 'UTF-8');
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$cnt = 1;
foreach ($xpath->query('//article') as $article) {
print $cnt . ' - ' . $article->nodeName . ' - ' . $article->getAttribute('id') . "\n";
$cnt += 1;
}

使用 file_get_contents 就像您之前尝试的那样:

<?php

$html = file_get_contents('http://www.emol.com/movil/nacional/');
$dom = new DOMDocument('1.0', 'UTF-8');
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$cnt = 1;
foreach ($xpath->query('//article') as $article) {
print $cnt . ' - ' . $article->nodeName . ' - ' . $article->getAttribute('id') . "\n";
$cnt += 1;
}

计数 30(使用 phpcasperjs)与 14(使用 file_get_contents)。

关于带有特定标记的 PHP DOM html 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48129698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com