gpt4 book ai didi

ruby - 如何抓取具有延迟加载的页面

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

这是我用于解析网页的代码。我是在 Rails 控制台中完成的。但是我在 Rails 控制台中没有得到任何输出。我想抓取的网站正在延迟加载

require 'nokogiri'
require 'open-uri'

page = 1
while true
url = "http://www.justdial.com/functions"+"/ajxsearch.php?national_search=0&act=pagination&city=Delhi+%2F+NCR&search=Pandits"+"&where=Delhi+Cantt&catid=1195&psearch=&prid=&page=#{page}"


doc = Nokogiri::HTML(open(url))
doc = Nokogiri::HTML(doc.at_css('#ajax').text)
d = doc.css(".rslwrp")
d.each do |t|
puts t.css(".jrcw").text
puts t.css("span.jcn").text
puts t.css(".jaid").text
puts t.css(".estd").text
page+=1
end
end

最佳答案

这里有两个选择:

  1. 将纯 HTTP 抓取切换到一些支持 javascript 评估的工具,例如 Capybara(选择了 proper driver)。这可能会很慢,因为您在后台运行 headless 浏览器,而且您必须设置一些超时或想出另一种方法来确保在开始任何抓取之前加载您感兴趣的文本 block 。

  2. 第二个选项是使用 Web Developer 控制台并弄清楚这些文本 block 是如何加载的(哪些 AJAX 调用、它们的参数等)并在您的抓取工具中实现它们。这是更高级的方法,但性能更高,因为您不会像在选项 1 中那样做任何额外的工作。

祝你有美好的一天!

更新:

上面的代码不起作用,因为响应是包装在 JSON 对象中的 HTML 代码,而您正试图将其解析为原始 HTML。它看起来像这样:

{
"error": 0,
"msg": "request successful",
"paidDocIds": "some ids here",
"itemStartIndex": 20,
"lastPageNum": 50,
"markup": 'LOTS AND LOTS AND LOTS OF MARKUP'
}

您需要解包 JSON,然后解析为 HTML:

require 'json' 

json = JSON.parse(open(url).read) # make sure you check http errors here
html = json['markup'] # can this field be empty? check for the json['error'] field
doc = Nokogiri::HTML(html) # parse as you like

我也会 advise you against使用 open-uri 因为如果由于 open-uri 的工作方式而使用动态 url,您的代码可能会变得容易受到攻击(阅读链接的文章了解详细信息)并使用 good and更多功能明智的库,例如 HTTPartyRestClient .

更新 2:对我来说最小的工作脚本:

require 'json'
require 'open-uri'
require 'nokogiri'

url = 'http://www.justdial.com/functions/ajxsearch.php?national_search=0&act=pagination&city=Delhi+%2F+NCR&search=Pandits&where=Delhi+Cantt&catid=1195&psearch=&prid=&page=2'

json = JSON.parse(open(url).read) # make sure you check http errors here
html = json['markup'] # can this field be empty? check for the json['error'] field
doc = Nokogiri::HTML(html) # parse as you like
puts doc.at_css('#newphoto10').attr('title')
# => Dr Raaj Batra Lal Kitab Expert in East Patel Nagar, Delhi

关于ruby - 如何抓取具有延迟加载的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32519620/

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