0

我正在尝试针对tr外部表中的表。外部表的第一个tr包含一个table带有标识表数据的图像。有几个带有不同图像的外部表,每种数据类型都有一个。我可以使用 Nokogiri 定位图像

page.css('table tr table tr img[@src="images/bicycyles.gif"]')

我想获取位于tr外部表第三个表中的数据。我可以使用页面上的所有数据

page.css('table[bgcolor="#FFFFFF"] tr[valign="top"]')

但这也会从其他数据类型中提取数据(例如,在“cars.gif”下)。

我怎样才能结合这些搜索来只找到自行车数据?我基本上想说“从trwithvalign=top中提取文本tablewith bgcolor=#ffffff,这是tr包含img src=bicycles.gif

这是 HTML 的示例:

<!-- Outer Table -->
<table>
    <tr>
        <td><img src="images/spacer.gif" width="1" height="10" /></td>
    </tr>
    <tr>
        <td>
            <table> 
                <tr>
                    <!-- Info must have this particular image preceding it -->
                    <td><img src="images/bicycle.gif" /></td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td><img src="images/spacer.gif" width="100" height="10" /></td>
    </tr>
    <tr>
        <td>
            <table width="532"> 
                <tr>
                    <td>Info</td>
                </tr>
            </table>
            <table bgcolor="#FFFFFF">
                <tr valign="top">
                    <!-- The info I want to extract -->
                    <td>Bicycle Name</td>
                </tr>
            </table>
        </td>
    </tr>
    <!-- More trs with different data types --> 
</table>
4

2 回答 2

1

tr“从withvalign=top中的tablewith 中提取文本bgcolor=#ffffff,它是tr包含 an的兄弟img src=bicycles.gif

基于示例 HTML 的轻微修正:

tr“从withvalign=top中的tablewith 中提取文本,该文本bgcolor=#ffffff包含在tr具有前一个tr兄弟的 a 中,该兄弟本身包含一个img src=bicycles.gif

转换为 XPath:

page.xpath('//tr[preceding-sibling::tr//img/@src = "images/bicycle.gif"]//table[@bgcolor="#FFFFFF"]//tr[@valign="top"]').text.strip

#=> "Bicycle Name"

请注意,在您给出的示例中,您要么需要,要么不需要[bgcolor="#FFFFFF"]两者[valign="top"]。由于依赖硬编码样式并不理想,因此您需要指定的越少越好。

于 2012-11-29T16:32:42.603 回答
0

我认为使用 css 仍然很混乱但更具可读性:

page.at('img[src="images/bicycle.gif"]').ancestors('tr')[1].at('~ tr tr[valign=top] td').text
#=> "Bicycle Name"
于 2012-11-30T00:31:38.150 回答