gpt4 book ai didi

ruby - `open_http' : 403 Forbidden (OpenURI::HTTPError) 字符串 "Steve_Jobs"但不是任何其他字符串

转载 作者:数据小太阳 更新时间:2023-10-29 06:49:34 27 4
gpt4 key购买 nike

我正在学习 http://ruby.bastardsbook.com/ 提供的 Ruby 教程我遇到了以下代码:

require "open-uri"

remote_base_url = "http://en.wikipedia.org/wiki"
r1 = "Steve_Wozniak"
r2 = "Steve_Jobs"
f1 = "my_copy_of-" + r1 + ".html"
f2 = "my_copy_of-" + r2 + ".html"

# read the first url
remote_full_url = remote_base_url + "/" + r1
rpage = open(remote_full_url).read

# write the first file to disk
file = open(f1, "w")
file.write(rpage)
file.close

# read the first url
remote_full_url = remote_base_url + "/" + r2
rpage = open(remote_full_url).read

# write the second file to disk
file = open(f2, "w")
file.write(rpage)
file.close

# open a new file:
compiled_file = open("apple-guys.html", "w")

# reopen the first and second files again
k1 = open(f1, "r")
k2 = open(f2, "r")

compiled_file.write(k1.read)
compiled_file.write(k2.read)

k1.close
k2.close
compiled_file.close

代码失败并显示以下痕迹:

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/open-uri.rb:277:in `open_http': 403 Forbidden (OpenURI::HTTPError)
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/open-uri.rb:616:in `buffer_open'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/open-uri.rb:164:in `open_loop'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/open-uri.rb:162:in `catch'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/open-uri.rb:162:in `open_loop'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/open-uri.rb:132:in `open_uri'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/open-uri.rb:518:in `open'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/open-uri.rb:30:in `open'
from /Users/arkidmitra/tweetfetch/samecode.rb:11

我的问题不是代码失败,而是每当我将 r2 更改为 Steve_Jobs 以外的任何内容时,它都能正常工作。这里发生了什么?

最佳答案

当我请求存在的 wiki 页面时,您的代码对我来说运行良好(Ruby MRI 1.9.3)。

当我请求一个不存在的 wiki 页面时,我得到一个 mediawiki 404 错误代码。

  • Steve_Jobs => 成功
  • Steve_Austin => 成功
  • Steve_Rogers => 成功
  • Steve_Foo => 错误

维基百科有缓存,所以如果您看到对“Steve_Jobs”的响应与其他确实存在的人不同,那么最好猜测这是因为维基百科正在缓存史蒂夫乔布斯的文章因为他很有名,并且可能会添加额外的检查/验证以保护文章免受快速更改、污损等。

适合您的解决方案:始终使用用户代理字符串打开 url。

rpage = open(remote_full_url, "User-Agent" => "Whatever you want here").read

来自 Mediawiki 文档的详细信息:“当您向 MediaWiki 网络服务 API 发出 HTTP 请求时,请务必指定一个正确标识您的客户端的 User-Agent header 。不要使用您的客户端提供的默认 User-Agent库,但组成一个自定义 header ,其中包括您的客户端的名称和版本号:类似于“MyCuteBot/0.1”。

在维基媒体 wiki 上,如果您不提供 User-Agent header ,或者您提供空的或通用的 header ,您的请求将失败并出现 HTTP 403 错误。请参阅我们的用户代理政策。”

关于ruby - `open_http' : 403 Forbidden (OpenURI::HTTPError) 字符串 "Steve_Jobs"但不是任何其他字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10925591/

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