gpt4 book ai didi

ruby - 我如何以这种特定方式解析此 Craigslist 页面?

转载 作者:数据小太阳 更新时间:2023-10-29 07:16:20 24 4
gpt4 key购买 nike

这是有问题的页面:http://phoenix.craigslist.org/cpg/

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

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

中的链接 href =>

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

我所做的只是简单地将所有 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.html
1=> 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 page
bq = doc.xpath('//blockquote')[1]

date = nil # Temp store of date of postings
posts = 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 collected
posts.each { |p| puts p.join(" - ") }

关于ruby - 我如何以这种特定方式解析此 Craigslist 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10791520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com