[英]XPath for td/th based on tr count
使用XPath进行webscrape。
结构是:
<table>
<tbody>
<tr>
<th>
<td>
但其中一个tr只包含一个或一个td。
<table>
<tbody>
<tr>
<th>
所以我只想在TR
里面包含两个标签。 我正在走这条路
$route = $path->query("//table[count(tr) > 1]//tr/th");
要么
$route = $path->query("//table[count(tr) > 1]//tr/td");
但它不起作用。
我在这里给出orjinal表的链接。 第一个表的最后两个TR只有一个TD。 这导致了问题。 第2或第3表也有同样的问题。
https://www.daiwahouse.co.jp/mansion/kanto/tokyo/y35/gaiyo.html
$route = $path->query("//tr[count(*) >= 2]/th");
foreach ($route as $th){
$property[] = trim($th->nodeValue);
}
$route = $path->query("//tr[count(*) >= 2]/td");
foreach ($route as $td){
$value[] = trim($td->nodeValue);
}
我试图同时选择TH和TD。 但是如果TR包含一个TD,那么就会发现问题。 因为在TD计数和TH计数不相同的情况下,我正在刮取更多TD然后TH
这个XPath,
//table[count(.//tr) > 1]/th
将选择所有th
所有内的元件table
具有元素多于一个tr
后代(不管是否tbody
存在)。
这个XPath,
//tr[count(*) > 1]/*
将选择具有多个子元素的tr
元素的所有子元素。
这个XPath,
//tr[count(th) = count(td)]/*
将选择tr
元素的所有子元素,其中th
元素的数量等于td
子元素的数量。
OP发布了该网站的链接。 根元素位于xmlns="http://www.w3.org/1999/xhtml"
命名空间中。
如果我理解正确的话,你想th
中的元素tr
s表示包含两个元素? 我认为这就是你需要的:
//th[count(../*) = 2]
我在答案中包含了一个更明确的路径,其中包含一个or
语句来计算TH和TD元素
$html = '
<html>
<body>
<table>
<tbody>
<tr>
<th>I am Included</th>
<td>I am a column</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<th>I am ignored</th>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<th>I am also Included</th>
<td>I am a column</td>
</tr>
</tbody>
</table>
</body>
</html>
';
$doc = new DOMDocument();
$doc->loadHTML( $html );
$xpath = new DOMXPath( $doc );
$result = $xpath->query("//table[ count( tbody/tr/td | tbody/tr/th ) > 1 ]/tbody/tr");
foreach( $result as $node )
{
var_dump( $doc->saveHTML( $node ) );
}
// string(88) "<tr><th>I am Included</th><td>I am a column</td></tr>"
// string(93) "<tr><th>I am also Included</th><td>I am a column</td></tr>"
您也可以将此用于任何深度后代
//table[ count( descendant::td | descendant::th ) > 1]//tr
在条件(方括号部分)之后更改xpath以更改返回的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.