0

我使用 Nokogiri 作为一个简单的示例来获取邮政编码的市政税带 (http://www.voa.gov.uk/cti/InitS.asp?lcn=0)

这是我目前拥有的代码:

 a = Mechanize.new{ |agent|  agent.user_agent_alias = 'Mac Safari'}
 a.get('http://www.voa.gov.uk/cti/InitS.asp?lcn=0') do |page|
      form = page.form_with(:id => "frmInitSForm")
      form.txtPostCode = "NN15 6UA"
      page = a.submit form

      page.search("tr").each do |tr|
        textF = tr.text.strip
        textF.gsub!(/[\n]+/, "\n")
        puts textF

      end

    end
  end

目前这会打印出里面的所有文本tr

然后我需要在里面do类似的东西

tdFirst = tr.children("td:first").text
tdSecond = tr.children("td:nth-child(2)").text

我如何获得firstsecondtd?

4

3 回答 3

2

在您的内部块中,尝试

tdFirst, tdSecond = tr.xpath('td')[0,2].map {|td| td.inner_text.strip}
puts "%s; %s" % [tdFirst, tdSecond]
于 2012-05-09T16:00:52.337 回答
2

使用 nokogiri 时,如果你已经有了tr,那么你可以使用

tds  = tr.xpath('td')
first = tds[0].text
second = tds[1].text
于 2012-05-09T15:55:24.467 回答
2

比获取所有 TDs 然后削减它更好,您可以像这样使用 XPath:

td1, td2 = tr.xpath('td[1 or 2]').map(&:text).map(&:strip)

或 CSS:

td1, td2 = tr.css('td:nth-child(1),td:nth-child(2)').map(&:text).map(&:strip)
于 2012-05-11T18:24:20.263 回答