从url-import网页搜索和使用数据

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

我尝试获取外部网站的源代码来加载它们并使用此代码。我需要处理一些div的内容 - 由类或特定名称命名。

起初我以这种方式获得源代码

$url='http://www.example.com/site.html';
$page = file_get_contents($url);

现在我必须在$ page中搜索一些div,例如搜索name =“test1”或class =“test2”的div,同样我还要查找其他一些元素,比如特定的名称或类。

现在我可以使用str_replace,探索等来构建一个长期无用的方式来做到这一点 - 有人可以告诉我如何以简单快捷的方式做到这一点?也许我可以在一种数组或其他东西中加载源代码?

非常感谢

对我来说,只有file_get_contents有效 - file_get_html不会工作!?

php
1个回答
1
投票

一个非常快速的基本示例,说明如何使用DOMDocumentDOMXPath查找页面中的元素。您将需要阅读我怀疑DOMDocumentDOMXPath的手册,并且可能找到一个好的XPath备忘单〜如this

$url='http://www.example.com/site.html';
$dom=new DOMDocument;
$dom->loadHTMLFile( $url );
$xp=new DOMXPath( $dom );

$query='//div[ contains( @class,"test" ) ]';
$col=$xp->query( $query );

if( $col && $col->length>0 ){
    foreach($col as $node)echo $node->nodeValue;
}
© www.soinside.com 2019 - 2024. All rights reserved.