gpt4 book ai didi

ruby - 使 headless 浏览器停止加载页面

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

我正在使用 watir-webdriver ruby​​ gem。它启动浏览器 (Chrome) 并开始加载页面。页面加载速度太慢,watir-webdriver 引发超时错误。如何让浏览器停止加载页面?

require 'watir-webdriver'

client = Selenium::WebDriver::Remote::Http::Default.new
client.timeout = 10
@browser = Watir::Browser.new :chrome, :http_client => client

sites = [
"http://google.com/",
"http://yahoo.com/",
"http://www.nst.com.my/", # => This is the SLOW site
"http://drupal.org/",
"http://www.msn.com/",
"http://stackoverflow.com/"
]

sites.each do |url|

begin
@browser.goto(url)
puts "Success #{url}"
rescue
puts "Timeout #{url}"
end

end

########## Execution result ##########

# Success http://google.com/
# Success http://yahoo.com/
# Timeout http://www.nst.com.my/
# Timeout http://drupal.org/
# Timeout http://www.msn.com/
# Timeout http://stackoverflow.com/

########## Expected result ##########

# Success http://google.com/
# Success http://yahoo.com/
# Timeout http://www.nst.com.my/
# Success http://drupal.org/
# Success http://www.msn.com/
# Success http://stackoverflow.com/

看起来浏览器在完成加载页面之前没有响应任何其他命令。如何强制浏览器放弃正在加载的页面并执行下一个命令?

更新

我发现了一个有趣的功能标志 loadAsync http://src.chromium.org/svn/trunk/src/chrome/test/webdriver/webdriver_capabilities_parser.cc也许它对解决这个问题有用?我还不明白如何让 watir (webdriver) 在启动 chromedriver 时设置它。这里介绍了这个标志http://codereview.chromium.org/7582005/

最佳答案

有几种不同的方法可以满足您的需求,但我会这样做:

require 'watir-webdriver'

client = Selenium::WebDriver::Remote::Http::Default.new
client.timeout = 60
@browser = Watir::Browser.new :firefox, :http_client => client

begin
@browser.goto mySite
rescue => e
puts "Browser timed out: #{e}"
end

next_command

如果您有很多站点要加载以确认是否超时,请将它们放在一个数组中:

mySites = [
mySite1,
mySite2,
mySite3
]

mySites.each do |site|
begin
@browser.goto site
rescue
"Puts #{site} failed to load within the time allotted."
end
end

概念验证更新。此脚本始终进行到第 2 步。对于第二个转到,救援甚至不是必需的,但用于更清晰的输出。您的脚本与此有何不同?

require 'watir-webdriver'

client = Selenium::WebDriver::Remote::Http::Default.new
client.timeout = 1 #VERY low timeout to make most sites fail
@browser = Watir::Browser.new :firefox, :http_client => client


def testing
begin
@browser.goto "http://www.cnn.com"
rescue => e
puts "Browser timed out on the first example"
end

begin
@browser.goto "http://www.foxnews.com"
rescue => e
puts "Browser timed out on the second example"
end
end

关于ruby - 使 headless 浏览器停止加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9876529/

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