【问题标题】:Getting a table with Mechanize in Ruby在 Ruby 中使用 Mechanize 获取表格
【发布时间】:2017-03-06 15:34:32
【问题描述】:

我想从这个表中获取项目:

<table style="margin: auto;width: 800px" id="myTable" class="tablesorter">
    <thead>
        <tr class="TableHeader">
            <th >Game</th><th>Icon</th><th>Achievement</th>
                                <th>Achievers</th>
                    <th>Value</th>
                        </tr>
    </thead>
    <tbody>
            <tr>
                        <td><a href="Steam_Game_Info.php?AppID=440"><img alt="Logo" src="http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/440/07385eb55b5ba974aebbe74d3c99626bda7920b8.jpg" width=133 height=50 ></a></td>
                        <td>    <table>
        <tr>
            <td class="AchievementBox" style="background-color: #347C17">
                <a href="Steam_Achievement_Info.php?AchievementID=169&amp;AppID=440">                <img  alt="Icon" src="http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/440/924764eea604817d3c14de9640ae6422c7cdfb7a.jpg" height='50' width='50'>
                </a>            </td>
        </tr>
    </table>
</td>
            <td style="text-align: left" ><a href="Steam_Achievement_Info.php?AchievementID=169&amp;AppID=440">Race for the Pennant</a><br>Run 25 kilometers.</td>
            <td style="text-align: right">35505</td><td style="text-align: right">1.3</td>

该表的 id 为 myTable,所以我想做的是:

go inside <tbody>
for each <tr> in table:
    do something; maybe go inside <td> or get a link from <href>

我有:

require 'mechanize'

agent = Mechanize.new
page = agent.get("http://astats.astats.nl/astats/TopListAchievements.php?DisplayType=2")

puts page.body

这会打印页面,但我如何实际遍历表格行?

【问题讨论】:

  • 看起来应该使用&lt;tbody&gt;&lt;thead&gt; 标签时要非常小心。很多时候,这些不在 HTML 源代码中,而是在您执行“查看源代码”时由浏览器放置在那里。如果您直接下载它们,它们将不会在 HTML 中看到,就像使用 Mechanize 一样,因此,您的选择器将失败。

标签: ruby web-scraping html-table nokogiri mechanize


【解决方案1】:

使用css选择器,打印文本和href属性值:

require 'nokogiri'
doc = Nokogiri::HTML(page.body)
doc.css('table#myTable tbody td[3] a').each {|a|
  puts a.text, a[:href]
}

【讨论】:

  • 我想我在您输入时进行了编辑...我如何获得描述(即跑 25 公里)?它们位于 标记 之后
  • 对“Run 25”执行 Ctrl + F 即可。目前该程序打印成就名称/链接。我希望它打印名称/链接/描述。
  • @N1ghtshade3,我明白了。试试p a.next.next.text(第一个next是获取&lt;br&gt;标签,第二个nexttext是获取文本)
  • 太棒了,谢谢。我想我开始明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多