我有下一个代码,当url直接打开时会获取http代码:
require 'net/http'
require 'uri'
def visit_page(url, response_code: false)
@browser.goto(url)
if response_code
page_status_code(url)
end
end
def page_status_code(url)
uri = URI.parse(url)
connection = Net::HTTP.new(uri.host, uri.port)
# If SSL.
# connection.use_ssl = true
# connection.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
response = connection.request(request)
response.code
end
在场景中,它看起来如下:
response_code = page.visit_page('https://www.google.com', response_code: true)
puts response_code
如果我单击链接,我如何应用它来获取 http 代码?
page.link_element(text: 'lorem ipsum').click
如果您单击锚标记并且它具有 href 属性,请尝试使用以下代码。
Hrefvalue = page.link_element(text: 'lorem ipsum').get_attribute ('href')
response_code = page.visit_page( Hrefvalue, response_code: true)
puts response_code
我找到了另一种解决方案:
mylink = @browser.link(:text, 'Lorem Ipsum')
url = URI.parse mylink.href
status_code = Net::HTTP.start(url.host, url.port) { |http| http.head(url.request_uri).code }
puts url
status_code.should == '200'
在这种情况下,我什至不需要单击链接,就会获得其代码。