ruby – 如何以这种特殊方式解析此Craigslist页面?

ruby – 如何以这种特殊方式解析此Craigslist页面?,第1张

概述这是有问题的页面: http://phoenix.craigslist.org/cpg/ 我想要做的是创建一个如下所示的数组: 日期(由该页面上的h4标记捕获)=>在单元格[0] [0] [0]中, 链接文字=>在单元格中[0] [1] [0] 链接href =>在单元格中[0] [1] [1] 即,在每一行中,我每行存储这些项目中的每一项. 我所做的只是将所有h4标签拉入并将其存储在这样的哈希中 这是有问题的页面: http://phoenix.craigslist.org/cpg/

我想要做的是创建一个如下所示的数组:

日期(由该页面上的h4标记捕获)=>在单元格[0] [0] [0]中,
链接文字=>在单元格中[0] [1] [0]
链接href =>在单元格中[0] [1] [1]

即,在每一行中,我每行存储这些项目中的每一项.

我所做的只是将所有h4标签拉入并将其存储在这样的哈希中:

contents2[link[:date]] = content_page.CSS("h4").text

这个问题是一个单元格存储整个页面上h4标签的所有文本…而我希望1个单元格有1个日期.

举个例子:

0 => Mon May 28 - Leads need follow up - (Phoenix) - http://phoenix.craigsList.org/wvl/cpg/3043296202.HTML1=> Mon May 28 - .Net/Java Developers - (phoenix) - http://phoenix.craigsList.org/cph/cpg/3043067349.HTML

任何关于我如何处理这个问题的想法都会非常感激.

解决方法 这个怎么样?

require 'rubygems'require 'open-uri'require 'nokogiri'doc = Nokogiri::HTML(open("http://phoenix.craigsList.org/cpg/"))# Postings start insIDe the second blockquote on the pagebq = doc.xpath('//blockquote')[1]date  = nil         # Temp store of date of postingsposts = Array.new   # Store array of all postings here# Loop through all blockquote children collecting data as we go along...bq.children.each { |nod|  # The date is stored in the h4 nodes. Grab it from there.  date = nod.text if nod.name == "h4"  # Skip nodes until we have a date  next if !date  # Skip nodes that are not p blocks. The p blocks contain the postings.  next if nod.name != "p"  # We have a p block. Extract posting data.  link = nod.CSS('a').first['href']  text = nod.text  # Add new posting to array  posts << [date,text,link]}# Output everything we just collectedposts.each { |p| puts p.join(" - ") }
总结

以上是内存溢出为你收集整理的ruby – 如何以这种特殊方式解析此Craigslist页面?全部内容,希望文章能够帮你解决ruby – 如何以这种特殊方式解析此Craigslist页面?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1293488.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-10
下一篇2022-06-10

发表评论

登录后才能评论

评论列表(0条)

    保存