weixin_42315761 2009-06-16 10:03
浏览 189
已采纳

缅怀一休之关于hpricot解析html文件的疑惑???

现有如下格式的html文件bar_list.html(需要解析的主要部分):
<table>
  <tbody>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
   </tr>
   <tr class="rowA">
      <td><a href="www.google.com"&gt;test value for a</a></td>
      <td>test value for b</td>
      <td>test value for c</td>
   </tr>
   <tr class="rowB">
      <td><a href="www.google.com"&gt;test value for a</a></td>
      <td>test value for b</td>
      <td>test value for c</td>
   </tr>
  </tbody>
</table>

现在目的是用Hpricot库提取class为rowA or rowB的tr标签下td的值插入数据库的某张表
也就是要提取test value for a | test value for b | test value for c (三个列)

请教熟练或精通正则表达式的前辈们指点一下,谢谢!

自己写了一段ruby script如下:


require 'rubygems'
require 'open-uri'
require 'hpricot'

local_html_url = "bar_list.html"

doc = Hpricot( open(local_html_url) )
(doc/"tr[@class ~= '(rowA|rowB)']").each do |row|
row.children.each do |column|
puts column.inner_html
end
end



遇到的疑惑:
1、tr[@class ~= '(rowA|rowB)']的目的是想要匹配class为rowA或rowB的所有tr元素,但无法匹配。单独用tr[@class ~= 'rowA'] 或 tr[@class ~= 'rowB']则可以。

2、 由于<tr>下的第一个<td>标签下的内容含有<a href="...">value</a>,现在只想要获取value,去掉a标签
不知用<a href="...">value</a>.sub(/regexp/, '') 这里的regexp不知怎么写。

3、由于要分别获取三个<td>下的值插入数据库表中所对应的列,而上述脚本获取的内容如下:
<a href="www.google.com"&gt;test value for a</a>
test value for b
test value for c
(因为用puts,所以出现了换行的效果,实际获得的三个<td>下的值是连续的。
像这样:<a href="www.google.com"&gt;test value for a</a>test value for btest value for c)





  • 写回答

1条回答 默认 最新

  • iteye_8302 2009-06-16 10:03
    关注

    这里不是正则表达式,是xpath,取内部值可以用inner_text,你可以写成这样:
    [code="ruby"]
    doc = Hpricot(open(local_html_url))
    p (doc/"tr[@class='rowA' or @class='rowB']/td").map(&:inner_text)
    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现