gpt4 book ai didi

ruby-on-rails - 如何在 Ruby 中打开 URL 并计算图像标签?

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

我正在尝试修改 Ruby SCSS 书中的这段代码:

require "open-uri"
url = "http://www.nytimes.com"
pattern = "<img"

page = open(url).read
tags = page.scan(pattern)
puts "The site #{url} has #{tags.length} img tags"

我想修改它,让程序请求一个 URL,然后对标签进行计数。我才编程几天。这是我的代码。它可能包含多个错误:

require "open-uri"
puts "Enter URL"
urlnew = gets
urlnew = URI.encode(urlnew)
URI.parse(urlnew)
page = open(urlnew).read
pattern = "<img"
tags = page.scan(pattern)
puts "The site #{url} has #{tags.length} img tags"

当我运行它时出现这个错误:

Enter URL                                                                                                                                                                                                                              
www.google.com
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/open-uri.rb:36:in `initialize': No such file or directory @ rb_sysopen - www.google.com%0A (Errno::ENOENT)
from /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/open-uri.rb:36:in `open'
from /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/open-uri.rb:36:in `open'
from /home/ubuntu/workspace/ruby/hello.rb:6:in `<main>'

我尝试了各种方法来获取 URL 输入。

Open an IO stream from a local file or url

似乎都没有用。如果您能提供帮助,谢谢。

最佳答案

使用 chomp 删除用户输入末尾出现的换行符

urlnew = gets.chomp

此外,请确保在 URL 中输入 http://。或者您可以将以下行添加到您的代码中

urlnew = "http://#{urlnew}" unless urlnew.start_with?("http://")

完整的工作程序如下:

require "open-uri"
puts "Enter URL"
urlnew = gets.chomp
urlnew = "http://#{urlnew}" unless urlnew.start_with?("http://")
urlnew = URI.encode(urlnew)
URI.parse(urlnew)
page = open(urlnew).read
pattern = "<img"
tags = page.scan(pattern)
puts "The site #{urlnew} has #{tags.length} img tags"

样本运行:

> ruby test.rb
Enter URL
stackoverflow.com
The site http://stackoverflow.com has 16 img tags

关于ruby-on-rails - 如何在 Ruby 中打开 URL 并计算图像标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34283039/

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