0

这可能只是一个语法问题。

我不清楚如何只匹配 id 以 rowId_ 开头的表行

agent = Mechanize.new
  pageC1 = agent.get("/customStrategyScreener!list.action") 

该表具有 class=tableCellDT。

 pageC1.search('table.tableCellDT tr[@id=rowId_]')  # parses OK but returns 0 rows since rowId_ is not matched exactly.

 pageC1.search('table.tableCellDT tr[@id=rowId_*]')  # Throws an error since * is not treated like a wildcard string match

示例 HTML:

 <table id="row" cellpadding="5" class="tableCellDT" cellspacing="1">
<thead>
<tr>
<th class="tableHeaderDT">#</th>
<th class="tableHeaderDT sortable">
<a href="?d-16544-s=1&amp;d-16544-o=2&amp;d-16544-p=1">Screener</a></th>
<th class="tableHeaderDT sortable">
<a href="?d-16544-s=2&amp;d-16544-o=2&amp;d-16544-p=1">Strategy</a></th>
<th class="tableHeaderDT"> </th></tr></thead>
<tbody>
<tr id="rowId_BullPut" class="odd">
<td>   1  </td>
<td>   Bull</td>
<td></td>
<td><a href="link1?model.itemId=2262">Edit</a>&nbsp;&nbsp;
            <a href="javascript:deleteScreener('link2?model.itemId=2262');">Delete</a>&nbsp;&nbsp;
            <a href="link3?model.itemId=2262&amp;amp;model.source=list">View</a>&nbsp;&nbsp;
            </td></tr>

笔记

pageC1是一个Mechanize::Page对象,而不是Nokogiri任何东西。抱歉,一开始不清楚。Mechanize::Page 没有#css 或#xpath 方法,但可以从中提取Nokogiri 文档(无论如何在内部使用)。

4

3 回答 3

2

要获取以“rowId_”开头的tr元素:id

pageC1.search('//tr[starts-with(@id, "rowId_")]')
于 2012-11-26T20:27:04.793 回答
1

您想要 CSS3属性以 selector 开头

pageC1.css('table.tableCellDT tr[id^="rowId_"]')

或 XPathstarts-with()函数:

pageC1.xpath('.//table[@class="tableCellDT"]//tr[starts-with(@id,"rowId_")]')

尽管 NokogiriNode#search方法会根据您编写的内容智能地在 CSS 或 XPath 选择器语法之间进行选择,但这并不意味着您可以在同一个查询中混合使用 CSS 和 XPath 选择器语法。

在行动:

>> require 'nokogiri'
#=> true

>> doc = Nokogiri.HTML <<ENDHTML; true #hide output from IRB
">> <table class="foo"><tr id="rowId_nonono"><td>Nope</td></tr></table>
">> <table class="tableCellDT">
">>   <tr id="rowId_yesyes"><td>Yes1</td></tr>
">>   <tr id="rowId_andme2"><td>Yes2</td></tr>
">>   <tr id="rowIdNONONO"><td>Needs underscore</td></tr>
">> </table>
">> ENDHTML
#=> true

>> doc.css('table.tableCellDT tr[id^="rowId_"]').map(&:text)
#=> ["Yes1", "Yes2"]

>> doc.xpath('.//table[@class="tableCellDT"]//tr[starts-with(@id,"rowId_")]').map(&:text)
#=> ["Yes1", "Yes2"]
于 2012-11-26T21:07:53.653 回答
0

感谢 http://nokogiri.org/Nokogiri/XML/Node.html#method-i-css

和上面的答案,这是解决我的问题的最终代码,即只获取我需要的行,然后只从每个行中读取某些信息:

 pageC1.search('//tr[starts-with(@id, "rowId_")]').each do |row|

# Read the string after _ in rowId_, part of the "id" in <tr>
    rid = row.attribute("id").text.split("_")[1] # => "BullPut"

# Get the URL of the 3rd <a> link in <td> cell 4    
    link = row.css("td[4] a[3]")[0].attributes["href"].text # => "link3?model.itemId=2262&amp;amp;model.source=list"
 end
于 2012-11-27T10:21:28.077 回答