[英]Scraping Webpage with DOMdocument and DOMXpath
我對此很陌生。 我想使用PHP從頁面中提取表,並在修改所有錨點的HREF值后返回HTML。 表格如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<link rel="stylesheet" type="text/css" href="../CssGraduateE.css">
<title></title>
</head>
<body>
<div>
<br>
<table class="main" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<br><span class="MainHeader">Subjects in Faculty - Electrical Engineering</span><br><br>
<table cellpadding="2" cellspacing="0" border="1" width="100%">
<tbody>
<tr>
<td><span class="SecondHeader"> Subject Number</span></td>
<td><span class="SecondHeader">Subject Name</span></td>
<td><span class="SecondHeader">Points</span></td>
<td><span class="SecondHeader">Semesters</span></td>
<td>Subject Site</td>
</tr>
<tr>
<td><a href="../Subjects/?SUB=46001">46001</a> </td>
<td nowrap="">Engineering of Distributed Software Sys</td>
<td>3</td>
<td><br></td>
<td><a target="_newtab" href="http://www.thislinkisok.com/courses/046001">www</a></td>
</tr>
<tr>
<td><a href="../Subjects/?SUB=46002">46002</a> </td>
<td nowrap="">Design and Analysis of Algorithms</td>
<td>3</td>
<td>B<br></td>
<td> <br></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<br>
<table border="0">
<tbody>
<tr>
<td>Last Update on :</td>
<td>Wednesday ,9 April 2014</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
我知道如何獲取我想要的表:$ query = $ xpath-> query('// table [@ class =“ main”] // table [1]'); 但是我如何遍歷所有以“ ../xxx”開頭的鏈接,並將其修改為如下形式:“ www.mynewlink.com/xxx”? 最后,我想將提取的表格返回為HTML。 如何使用本機DOMDocument和DOMXpath做到這一點?
謝謝大家!
如果$html
是從外部網站獲取的HTML字符串,則可以執行以下操作:
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach($xpath->query('//table[@class="main"]//a[starts-with(@href, "../")]') as $link) {
$link->setAttribute('href', preg_replace('#^..#', 'http://www.mynewlink.com', $link->getAttribute('href')));
}
$container = new DOMDocument();
$container->appendChild($container->importNode($xpath->query('//table[@class="main"]')->item(0), true));
echo $container->saveHTML();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.