gpt4 book ai didi

ruby - 使用 Anemone Web Spider 进行 HTTP 基本身份验证

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

我需要从站点的所有页面收集所有“标题”。
站点具有 HTTP 基本身份验证配置。
没有授权我接下来做:

require 'anemone'
Anemone.crawl("http://example.com/") do |anemone|
anemone.on_every_page do |page|
puts page.doc.at('title').inner_html rescue nil
end
end

但是我对 HTTP Basic Auth 有一些问题...
如何使用 HTTP Basic Auth 从站点收集标题?
如果我尝试使用“Anemone.crawl(” http://username:password@example.com/ “)”,那么我只有第一页标题,但其他链接有 http://example.com/样式,我收到 401 错误。

最佳答案

HTTP 基本身份验证通过 HTTP header 工作。愿意访问受限资源的客户端必须提供身份验证 header ,如下所示:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

它包含名称和密码,Base64 编码。更多信息在维基百科文章中:Basic Access Authentication .

我用谷歌搜索了一下,没有找到让 Anemone 接受自定义请求 header 的方法。也许你会有更多的运气。

但我发现了另一个声称可以做到的爬虫:Messie .也许你应该试一试

更新

这是 Anemone 设置其请求 header 的地方:Anemone::HTTP .事实上,那里没有定制。你可以猴子修补它。像这样的东西应该可以工作(把它放在你的应用程序的某个地方):

module Anemone
class HTTP
def get_response(url, referer = nil)
full_path = url.query.nil? ? url.path : "#{url.path}?#{url.query}"

opts = {}
opts['User-Agent'] = user_agent if user_agent
opts['Referer'] = referer.to_s if referer
opts['Cookie'] = @cookie_store.to_s unless @cookie_store.empty? || (!accept_cookies? && @opts[:cookies].nil?)

retries = 0
begin
start = Time.now()
# format request
req = Net::HTTP::Get.new(full_path, opts)
response = connection(url).request(req)
finish = Time.now()
# HTTP Basic authentication
req.basic_auth 'your username', 'your password' # <<== tweak here
response_time = ((finish - start) * 1000).round
@cookie_store.merge!(response['Set-Cookie']) if accept_cookies?
return response, response_time
rescue Timeout::Error, Net::HTTPBadResponse, EOFError => e
puts e.inspect if verbose?
refresh_connection(url)
retries += 1
retry unless retries > 3
end
end
end
end

显然,您应该为 basic_auth 方法调用提供您自己的 usernamepassword 参数值。是的,它又快又脏又硬编码。但有时你没有时间以适当的方式做事。 :)

关于ruby - 使用 Anemone Web Spider 进行 HTTP 基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16846089/

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