gpt4 book ai didi

html - nokogiri 从选定的 div 中抓取所有子 div

转载 作者:太空宇宙 更新时间:2023-11-03 22:47:16 24 4
gpt4 key购买 nike

我在空闲时间玩 Nokogiri,恐怕我真的卡住了。我从今天早上开始尝试解决这个问题(现在差不多 8 小时 :( ) 看起来我没有进步所有。在 website 上,我想抓取页面上的所有线程。到目前为止,我意识到所有线程的父级是

<div id="threads" class="extended-small">

每个线程由三个元素组成:

  1. 图片链接
  2. div#title 包含 replies(R) 和 images(I) 的值
  3. 包含话题名称的div#teaser

我的问题是如何选择 id='threads' 的子项并将每个具有 3 个元素的 child 插入数组?正如您在这段代码中看到的,我真的不知道自己在做什么,我非常非常感谢

require 'httparty'
require 'nokogiri'
require 'json'
require 'pry'
require 'csv'

page = HTTParty.get('https://boards.4chan.org/g/catalog')

parse_page = Nokogiri::HTML(page)

threads_array = []

threads = parse_page.search('.//*[@id="threads"]/div') do |a|
post_id = a.text
post_pic = a.text
post_title = a.text
post_teaser = a.text
threads_array.push(post_id,post_pic,post_title,post_teaser)
end

CSV.open('sample.csv','w') do |csv|
csv << threads_array
end

Pry.start(binding)

page and code

最佳答案

看起来原始 HTML 源代码不包含这些字段,这就是为什么您在使用 HTTParty 和 Nokogiri 进行解析时看不到它的原因。看起来他们将数据放在更远的 JS 变量中。试试这个:

require 'rubygems'
require 'httparty'
require 'json'

page = HTTParty.get('https://boards.4chan.org/g/catalog')
m = page.match(/var catalog = ({.*?});var/)
json_str = m.captures.first
catalog = JSON.parse(json_str)
pp catalog

这是否足够强大我会让你决定:)

关于html - nokogiri 从选定的 div 中抓取所有子 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41524951/

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