连接单个 XPath 查询的多个结果

Concatenating multiple results of a single XPath query

给定以下 HTML table:

<table>
    <tbody>
        <tr>
            <td>
                <a href="">Example 1</a>
                , 
                <a href="">Example 2</a>
            </td>
        </tr>
        <tr>
            <td>
                <a href="">Example 1</a>
                , 
                <a href="">Example 2</a>
                , 
                <a href="">Example 3</a>
            </td>
        </tr>
        <!-- ... -->
        <!-- Variable amount of rows with variable amount of anchor texts -->
        <!-- ... -->
    </tbody>
 </table>

是否可以通过单个 XPath 查询获得以下结果?

  1. Example 1, Example 2

  2. Example 1, Example 2, Example 3


我试过了:

string(/table/tbody/tr/td//node())

这显然行不通,原因如下:

string(object?)

converts any of the four XPath data types into a string according to built-in rules. If the value of the argument is a node-set, the function returns the string-value of the first node in document order, ignoring any further nodes.

-- Wikipedia


编辑

我使用了 PHP 的 XPath support,它只支持 v1.0。

XPath 查询旨在由用户插入我正在构建的网络抓取工具库的配置文件中。

在 XPath 2.0 中你可以做到

//tr/string-join(.//a/text(), ", ")

//tr/string(normalize-space(td))

get output

Example 1, Example 2
Example 1, Example 2, Example 3

您也可以使用编程语言libs/features 来获取输出(如果您需要 XPath 1.0 解决方案)。例如,使用 Python lxml.html

for tr in source.xpath('//tr'):
    print(', '.join([a.text for a in tr.xpath('./td/a')]))