This man is too old to remember everything in his brain. Right now, he needs a place to write down what he has studied.
標籤
4GL
(1)
人才發展
(10)
人物
(3)
太陽能
(4)
心理
(3)
心靈
(10)
文學
(31)
生活常識
(14)
光學
(1)
名句
(10)
即時通訊軟體
(2)
奇狐
(2)
爬蟲
(1)
音樂
(2)
產業
(5)
郭語錄
(3)
無聊
(3)
統計
(4)
新聞
(1)
經濟學
(1)
經營管理
(42)
解析度
(1)
遊戲
(5)
電學
(1)
網管
(10)
廣告
(1)
數學
(1)
機率
(1)
雜趣
(1)
證券
(4)
證券期貨
(1)
ABAP
(15)
AD
(1)
agentflow
(4)
AJAX
(1)
Android
(1)
AnyChart
(1)
Apache
(14)
BASIS
(4)
BDL
(1)
C#
(1)
Church
(1)
CIE
(1)
CO
(38)
Converter
(1)
cron
(1)
CSS
(23)
DMS
(1)
DVD
(1)
Eclipse
(1)
English
(1)
excel
(5)
Exchange
(4)
Failover
(1)
Fedora
(1)
FI
(57)
File Transfer
(1)
Firefox
(3)
FM
(2)
fourjs
(1)
Genero
(1)
gladiatus
(1)
google
(1)
Google Maps API
(2)
grep
(1)
Grub
(1)
HR
(2)
html
(23)
HTS
(8)
IE
(1)
IE 8
(1)
IIS
(1)
IMAP
(3)
Internet Explorer
(1)
java
(4)
JavaScript
(22)
jQuery
(6)
JSON
(1)
K3b
(1)
ldd
(1)
LED
(3)
Linux
(120)
Linux Mint
(4)
Load Balance
(1)
Microsoft
(2)
MIS
(2)
MM
(51)
MSSQL
(1)
MySQL
(27)
Network
(1)
NFS
(1)
Office
(1)
OpenSSL
(1)
Oracle
(131)
Outlook
(3)
PDF
(6)
Perl
(60)
PHP
(33)
PL/SQL
(1)
PL/SQL Developer
(1)
PM
(3)
Postfix
(2)
postfwd
(1)
PostgreSQL
(1)
PP
(50)
python
(5)
QM
(1)
Red Hat
(4)
Reporting Service
(28)
ruby
(11)
SAP
(234)
scp
(1)
SD
(16)
sed
(1)
Selenium
(3)
Selenium-WebDriver
(5)
shell
(5)
SQL
(4)
SQL server
(8)
sqlplus
(1)
SQuirreL SQL Client
(1)
SSH
(3)
SWOT
(3)
Symantec
(2)
T-SQL
(7)
Tera Term
(2)
tip
(1)
tiptop
(24)
Tomcat
(6)
Trouble Shooting
(1)
Tuning
(5)
Ubuntu
(37)
ufw
(1)
utf-8
(1)
VIM
(11)
Virtual Machine
(2)
VirtualBox
(1)
vnc
(3)
Web Service
(2)
wget
(1)
Windows
(19)
Windows
(1)
WM
(6)
Xvfb
(2)
youtube
(1)
yum
(2)
2013年11月10日 星期日
操作combobox下拉式選單
#@driver.find_element(:id, "login_server").SelectByText("領域 7")
select = @driver.find_element(:id, 'login_server')
option = Selenium::WebDriver::Support::Select.new(select)
#option.select_by(:text, '領域 7')
option.select_by(:index, 6)
2013年9月17日 星期二
安裝 gem install selenium-webdriver 出現錯誤
Building native extensions. This could take a while...
ERROR: Error installing selenium-webdriver:
ERROR: Failed to build gem native extension.
/usr/bin/ruby extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/ruby.h
Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/ffi-1.9.0 for inspection.
Results logged to /usr/lib/ruby/gems/1.8/gems/ffi-1.9.0/ext/ffi_c/gem_make.out
=========================================================================
solution : yum install ruby-devel
2013年1月1日 星期二
ruby : 二維array排序
升冪排序
tyruan@Ubuntu:~$
tyruan@Ubuntu:~$ ruby
a=[[1,3],[2,1],[3,5]]
b=a.sort_by{|x| x[1]}
puts "#{b}"
__END__
211335
降冪排序
a=[[1,3],[2,1],[3,5]]
b=a.sort {|x,y| y[1] <=> x[1]}
puts "#{b}"
[[3, 5], [1, 3], [2, 1]]
不知道降冪排序為何sort_by 沒有用,而sort可以???
tyruan@Ubuntu:~$
tyruan@Ubuntu:~$ ruby
a=[[1,3],[2,1],[3,5]]
b=a.sort_by{|x| x[1]}
puts "#{b}"
__END__
211335
降冪排序
a=[[1,3],[2,1],[3,5]]
b=a.sort {|x,y| y[1] <=> x[1]}
puts "#{b}"
[[3, 5], [1, 3], [2, 1]]
不知道降冪排序為何sort_by 沒有用,而sort可以???
ruby : Custom Firefox path
http://code.google.com/p/selenium/wiki/RubyBindings
Custom Firefox path
If your Firefox executable is in a non-standard location:Selenium::WebDriver::Firefox.path = "/path/to/firefox" driver = Selenium::WebDriver.for :firefox
2012年12月12日 星期三
Selenium-WebDriver : Windows Authentication firefox
我試了好久,很多網頁上沒有講清楚,所以我將步驟寫下:
prerequsites :
1. firefox profile :在 開始->執行->firefox.exe -ProfileManager
2. 預設有 "default" 的profile,如果有需要,可以自行create另一個profile供selenium-webdriver使用
3. 在firefox的 工具->選項->安全->已存密碼 確認target URL的username/password已經被存入
4. 如果item 3沒有看到username/password,則手動login 進入target URL,做一次login,firefox會自動記錄username/password
5. 要注意,當某profile被firefox開起來 時,selenium-webdriver是無法開啟同一profile的,因為被lock住了。
6. 我看到有些網站說要用AutoAuth的add-on附加元件。
新版firefox(我不確定從何版本開始,但我使用的是17.0.1)不用;
但是3.6.17 (on Ubuntu 9.10)就需要...
7. 很多網站說要改about:config...我的感覺有點在畫老虎,畫蘭花... :D
8. 還有網站寫driver.get("http://username:password@example.com")的方式,這是for basic authentication,不是for Windows authentication
source code :
require 'rubygems' #windows平台可以不要此行
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox, :profile => "default"
#profile要指定是重點,因為沒有指定的話,selenium-webdriver是不會用任何 firefox profile的
driver.get "http://xxx/ReportServer/Pages/ReportViewer.aspx?yyy&rs:Command=Render"
prerequsites :
1. firefox profile :在 開始->執行->firefox.exe -ProfileManager
2. 預設有 "default" 的profile,如果有需要,可以自行create另一個profile供selenium-webdriver使用
3. 在firefox的 工具->選項->安全->已存密碼 確認target URL的username/password已經被存入
4. 如果item 3沒有看到username/password,則手動login 進入target URL,做一次login,firefox會自動記錄username/password
5. 要注意,當某profile被firefox開起來 時,selenium-webdriver是無法開啟同一profile的,因為被lock住了。
6. 我看到有些網站說要用AutoAuth的add-on附加元件。
新版firefox(我不確定從何版本開始,但我使用的是17.0.1)不用;
但是3.6.17 (on Ubuntu 9.10)就需要...
7. 很多網站說要改about:config...我的感覺有點在畫老虎,畫蘭花... :D
8. 還有網站寫driver.get("http://username:password@example.com")的方式,這是for basic authentication,不是for Windows authentication
source code :
require 'rubygems' #windows平台可以不要此行
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox, :profile => "default"
#profile要指定是重點,因為沒有指定的話,selenium-webdriver是不會用任何 firefox profile的
driver.get "http://xxx/ReportServer/Pages/ReportViewer.aspx?yyy&rs:Command=Render"
Ruby + selenium-webdriver : get Screenshot
require 'rubygems'
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
driver.get "https://www.google.com"
driver.save_screenshot("./screen.png")
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
driver.get "https://www.google.com"
driver.save_screenshot("./screen.png")
2012年12月9日 星期日
ruby 時間方法總結
# 生成一个当前时间的对象
day = Time.now
# 当前时间
p day.to_s
# 年
p day.year
# 月
p day.month
# 日
p day.day
# 小时
p day.hour
# 分
p day.min
# 秒
p day.sec
# 星期(0为星期日, 1为星期一, ... )
p day.wday
strftime 方法中可用的格式化符号
%A: 星期的名称(如:Sunday, Monday ... )
%a: 星期的名称缩写(如:Sun, Mon ... )
%B: 月份的名称(如:January, February ... )
%b: 月份的名称缩写(如:Jan, Feb ... )
%c: 日期,时刻(如:02/23/10 16:43:49)
%d: 日(01-31)
%H: 24小时制的时间(00-23)
%I:
%j:
%M: 分(00-59)
%m: 月(01-12)
%p: 午前和午后(AM,PM)
%S: 秒(00-60)
%w: 一周的天数,周日(0)开始算起(0-6)
%X: 时刻
%x: 日期
%Y: 表示4位数年份(如:2010)
%y: 表示2位数年份(如:10)
%Z: 时区
%%: 显示%符号自身
Example:
Ruby代码
day = Time.now
puts day.strftime("Now, %A %B %d %X %Z %Y")
当前日期
require 'date'
day = Date::new(2010, 2, 23)
p day.to_s
昨天, 明天
require 'date'
day = Date.new(2010, 2, 23)
day = day + 1
p day.to_s
day = Date.new(2010, 2, 23)
day = day - 1
p day.to_s
下月,上月
require 'date'
day = Date.new(2010, 2, 23)
day = day >> 1
p day.to_s
day = Date.new(2010, 2, 23)
day = day << 1
p day.to_s
闰年
require 'date'
p day.leap?
day = Date.new(2010)
p day.leap?
日期的格式化
require 'date'
day = Date::new(2010, 2, 23)
p day.year
p day.month
p day.day
p day.wday
2012年12月7日 星期五
Selenium-WebDriver : drag_and_drop, find_elements (contains)
http://selenium.googlecode.com/svn/trunk/docs/api/rb/Selenium/WebDriver/ActionBuilder.html
driver.action.key_down(:shift). click(element). click(second_element). key_up(:shift). drag_and_drop(element, third_element). perform
heals = @wait.until {@driver.find_elements(:xpath,"//img[contains(@src,'7263/img/item/7_')]")}
Selenium-WebDriver : Explicit and Implicit Waits
http://seleniumhq.org/docs/04_webdriver_advanced.html
This waits up to 10 seconds before throwing a TimeoutException or if
it finds the element will return it in 0 - 10 seconds.
WebDriverWait by default calls the ExpectedCondition every 500
milliseconds until it returns successfully. A successful return is
for ExpectedCondition type is Boolean return true or not null return
value for all other ExpectedCondition types.
This example is also functionally equivalent to the first Implicit Waits example.
The ExpectedConditions class in contains a set of predefined conditions to use with WebDriverWait in Java.
The Advanced User Interactions require native events to be enabled. Here’s a table of the current support Matrix for native events:
Topics to be included:
WebDriver: Advanced Usage
Explicit and Implicit Waits
Waiting is having the automated task execution elapse a certain amount of time before continuing with the next step.Explicit Waits
An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(new ExpectedCondition<WebElement>(){
@Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("myDynamicElement"));
}});
IWebDriver driver = new FirefoxDriver();
driver.Url = "http://somedomain/url_that_delays_loading";
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.Id("someDynamicElement"));
});
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
ff = webdriver.Firefox()
ff.get("http://somedomain/url_that_delays_loading")
try:
element = WebDriverWait(ff, 10).until(lambda driver : driver.find_element_by_id("myDynamicElement"))
finally:
ff.quit()
require 'rubygems' # not required for ruby 1.9 or if you installed without gem
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
driver.get "http://somedomain/url_that_delays_loading"
wait = Selenium::WebDriver::Wait.new(:timeout => 10) # seconds
begin
element = wait.until { driver.find_element(:id => "some-dynamic-element") }
ensure
driver.quit
end
This example is also functionally equivalent to the first Implicit Waits example.
Expected Conditions
There are some common conditions that are frequently come across when automating web browsers. Listed below are Implementations of each. Java happens to have convienence methods so you don’t have to code an ExpectedCondition class yourself or create your own utility package for them.- Element is Clickable - it is Displayed and Enabled.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
wait = WebDriverWait(driver, 10)
def clickable(element):
if element.is_clickable():
return element
return null
element = wait.until(lambda d: clickable(d.find_element_by_id('someid')))
Implicit Waits
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
WebDriver driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
driver.Url = "http://somedomain/url_that_delays_loading";
IWebElement myDynamicElement = driver.FindElement(By.Id("someDynamicElement"));
from selenium import webdriver
ff = webdriver.Firefox()
ff.implicitly_wait(10) # seconds
ff.get("http://somedomain/url_that_delays_loading")
myDynamicElement = ff.find_element_by_id("myDynamicElement")
require 'rubygems' # not required for ruby 1.9 or if you installed without gem
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
driver.manage.timeouts.implicit_wait = 10 # seconds
driver.get "http://somedomain/url_that_delays_loading"
element = driver.find_element(:id => "some-dynamic-element")
RemoteWebDriver
Taking a Screenshot
import java.io.File;
import java.net.URL;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class Testing {
public void myTest() throws Exception {
WebDriver driver = new RemoteWebDriver(
new URL("http://localhost:4444/wd/hub"),
DesiredCapabilities.firefox());
driver.get("http://www.google.com");
// RemoteWebDriver does not implement the TakesScreenshot class
// if the driver does have the Capabilities to take a screenshot
// then Augmenter will add the TakesScreenshot methods to the instance
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenshot = ((TakesScreenshot)augmentedDriver).
getScreenshotAs(OutputType.FILE);
}
}
// Add this class to your code and use this instead of RemoteWebDriver
// You will then be able to cast it to ITakesScreenshot and call GetScreenshot
public class ScreenShotRemoteWebDriver : RemoteWebDriver, ITakesScreenshot
{
public ScreenShotRemoteWebDriver(Uri RemoteAdress, ICapabilities capabilities)
: base(RemoteAdress, capabilities)
{
}
/// <summary>
/// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen.
/// </summary>
/// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
public Screenshot GetScreenshot()
{
// Get the screenshot as base64.
Response screenshotResponse = this.Execute(DriverCommand.Screenshot, null);
string base64 = screenshotResponse.Value.ToString();
// ... and convert it.
return new Screenshot(base64);
}
}
// And then the usage would be:
ScreenShotRemoteWebDriver webDriver = new ScreenShotRemoteWebDriver(new Uri("http://127.0.0.1:4444/wd/hub"), DesiredCapabilities.Firefox());
// ... do stuff with webDriver
Screenshot ss = ((ITakesScreenshot)webDriver).GetScreenshot();
string screenshot = ss.AsBase64EncodedString;
byte[] screenshotAsByteArray = ss.AsByteArray;
ss.SaveAsFile(activeDir + TestSuiteName + "//" + FileNanme + imageFormat, ImageFormat.Jpeg);
from selenium import webdriver
driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.FIREFOX)
driver.get("http://www.google.com")
driver.get_screenshot_as_file('/Screenshots/google.png')
require 'rubygems'
require 'selenium-webdriver'
begin
driver = Selenium::WebDriver.for :remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => :firefox
driver.get "http://www.google.com"
driver.save_screenshot "/Screenshots/google.png"
ensure
driver.quit
end
Using a FirefoxProfile
FirefoxProfile fp = new FirefoxProfile();
// set something on the profile...
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setCapability(FirefoxDriver.PROFILE, fp);
WebDriver driver = new RemoteWebDriver(dc);
from selenium import webdriver
fp = webdriver.FirefoxProfile()
# set something on the profile...
driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.FIREFOX, browser_profile=fp)
Using ChromeOptions
ChromeOptions options = new ChromeOptions();
// set some options
DesiredCapabilities dc = DesiredCapabilities.chrome();
dc.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new RemoteWebDriver(dc);
from selenium import webdriver
options = webdriver.ChromeOptions()
# set some options
driver = webdriver.Remote(desired_capabilities=options.to_capabilities())
AdvancedUserInteractions
The Actions class(es) allow you to build a Chain of Actions and perform them. There are too many possible combinations to count. Below are a few of the common interactions that you may want to use. For a full list of actions please refer to the API docs Java C# Ruby PythonThe Advanced User Interactions require native events to be enabled. Here’s a table of the current support Matrix for native events:
| platform | IE6 | IE7 | IE8 | IE9 | FF3.6 | FF10+ | Chrome stable | Chrome beta | Chrome dev | Opera | Android | iOS |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Windows XP | Y | Y | Y | n/a | Y | Y | Y | Y | Y | ? | Y [1] | n/a |
| Windows 7 | n/a | n/a | Y | Y | Y | Y | Y | Y | Y | ? | Y [1] | n/a |
| Linux (Ubuntu) | n/a | n/a | n/a | n/a | Y [2] | Y [2] | Y | Y | Y | ? | Y [1] | n/a |
| Mac OSX | n/a | n/a | n/a | n/a | N | N | Y | Y | Y | ? | Y [1] | N |
| Mobile Device | n/a | n/a | n/a | n/a | n/a | ? | n/a | n/a | n/a | ? | Y | N |
| [1] | (1, 2, 3, 4) Using the emulator |
| [2] | (1, 2) With explicitly enabling native events |
Browser Startup Manipulation
TodoTopics to be included:
- restoring cookies
- changing firefox profile
- running browsers with plugins
Using a Proxy
Internet Explorer
The easiest and recommended way is to manually set the proxy on the machine that will be running the test. If that is not possible or you want your test to run with a different configuration or proxy, then you can use the following technique that uses a Capababilities object. This temporarily changes the system’s proxy settings and changes them back to the original state when done.String PROXY = "localhost:8080";
org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setHttpProxy(PROXY)
.setFtpProxy(PROXY)
.setSslProxy(PROXY);
DesiredCapabilities cap = new DesiredCapabailities();
cap.setPreference(CapabilityType.PROXY, proxy);
WebDriver driver = new InternetExplorerDriver(cap);
from selenium import webdriver
PROXY = "localhost:8080"
webdriver.DesiredCapabilities.INTERNETEXPLORER['proxy'] = {
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
"noProxy":None,
"proxyType":"MANUAL",
"class":"org.openqa.selenium.Proxy",
"autodetect":False
}
# you have to use remote, otherwise you'll have to code it yourself in python to
# dynamically changing the system proxy preferences
driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.INTERNETEXPLORER)
require 'rubygems'
require 'selenium-webdriver'
PROXY = "localhost:8080"
proxy = Selenium::WebDriver::Proxy.new(
:http => PROXY,
:ftp => PROXY,
:ssl => PROXY
)
caps = Selenium::WebDriver::Remote::Capabilities.ie(:proxy => proxy)
# you have to use remote, otherwise you'll have to code it yourself in ruby to
# dynamically changing the system proxy preferences
driver = Selenium::WebDriver.for :remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => caps
Chrome
Is basically the same as internet explorer. It uses the same configuration on the machine as IE does (on windows). On Mac it uses the System Preference -> Network settings. On Linux it uses (on Ubuntu) System > Preferences > Network Proxy Preferences (Alternatively in “/etc/environment” set http_proxy). As of this writing it is unknown how to set the proxy programmatically.Firefox
Firefox maintains it’s proxy configuration in a profile. You can preset the proxy in a profile and use that Firefox Profile or you can set it on profile that is created on the fly as is shown in the following example.String PROXY = "localhost:8080";
org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setHttpProxy(PROXY)
.setFtpProxy(PROXY)
.setSslProxy(PROXY);
DesiredCapabilities cap = new DesiredCapabailities();
cap.setPreference(CapabilityType.PROXY, proxy);
WebDriver driver = new FirefoxDriver(cap);
from selenium import webdriver
PROXY_HOST = "host"
PROXY_PORT = 8080
fp = webdriver.FirefoxProfile()
# Direct = 0, Manual = 1, PAC = 2, AUTODETECT = 4, SYSTEM = 5
fp.set_preference("network.proxy.type", 1)
fp.set_preference("network.proxy.http", PROXY_HOST)
fp.set_preference("network.proxy.http_port", PROXY_PORT)
fp.set_preference("network.proxy.ftp", PROXY_HOST)
fp.set_preference("network.proxy.ftp_port", PROXY_PORT)
fp.set_preference("network.proxy.ssl", PROXY_HOST)
fp.set_preference("network.proxy.ssl_port", PROXY_PORT)
fp.set_preference("network.proxy.no_proxies_on", "") # set this value as desired
driver = webdriver.Firefox(firefox_profile=fp)
require 'rubygems'
require 'selenium-webdriver'
PROXY = 'localhost:8087'
profile = Selenium::WebDriver::Firefox::Profile.new
profile.proxy = Selenium::WebDriver::Proxy.new(
:http => PROXY,
:ftp => PROXY,
:ssl => PROXY
)
driver = Selenium::WebDriver.for :firefox, :profile => profile
Opera
TodoHTML5
TodoParallelizing Your Test Runs
Todo2012年12月6日 星期四
Command-line Arguments
http://ruby.about.com/od/rubyfeatures/a/argv.htm
Many Ruby scripts have no text or graphical interfaces. They simply run, do their job and then exit. To communicate with these scripts in order to change their behavior, command-line arguments must be used. This is the standard mode of operation for UNIX commands and since Ruby is used widely on UNIX and UNIX-like systems (such as Linux and OS X), it's pretty standard to encounter this type of program.
Providing Command-line Arguments
Command-line arguments are passed to the Ruby program by the shell, the program the excepts commands (such as bash)on the terminal. On the command-line, any text following the name of the script is considered a command-line argument. Separated by spaces, each word or string will be passed as a separate argument to the Ruby program. The following example shows how to launch the test.rb Ruby script from a command-line with the arguments test1 and test2.$ ./test.rb test1 test2You may encounter a situation in which you need to pass an argument with a space in it to a Ruby program. It seems impossible at first, since the shell separates arguments on spaces. However, there is a provision for this: any arguments in double quotes will not be separated. The double quotes are removed by the shell before passing it to the Ruby program. The following example passes a single argument to the test.rb Ruby script, test1 test2.
$ ./test.rb "test1 test2"
Using Command-line Arguments
In your Ruby programs, you can access any command-line arguments passed by the shell with the ARGV special variable. ARGV is an Array variable which holds, as strings, each argument passed by the shell. The following program iterates over the ARGV array and prints out its contents.#!/usr/bin/env rubyThe following is an excerpt of a bash session launching this script (saved as the file test.rb) with a variety of arguments.
ARGV.each do|a|
puts "Argument: #{a}"
end
$ ./test.rb test1 test2 "three four"
Argument: test1
Argument: test2
Argument: three four
2012年12月5日 星期三
ruby for gladiatus in Ubuntu
~$ sudo apt-get install ruby
~$ sudo apt-get install rubygems
~$ sudo gem install selenium-webdriver (換瀏覽器版本時,重新執行此指令)
~$ sudo gem install oj #for 不要出現 [WARNING] MultiJson is using the default adapter (ok_json). We recommend loading a different JSON library to improve performance.
~$ vi attack.rb
~$ vi glad-methods.rb
attack.rb
~$ sudo apt-get install rubygems
~$ sudo gem install selenium-webdriver (換瀏覽器版本時,重新執行此指令)
~$ sudo gem install oj #for 不要出現 [WARNING] MultiJson is using the default adapter (ok_json). We recommend loading a different JSON library to improve performance.
~$ vi attack.rb
~$ vi glad-methods.rb
attack.rb
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
require 'rubygems'
require 'selenium-webdriver'
load 'glad-methods.rb'
if ARGV[0] == "1"
puts "login1"
login1
elsif ARGV[0] == "5"
puts "login5"
login5
elsif ARGV[0] == "7"
puts "login7"
login7
end
def attack
#為了防備中午12:00~13:00公司internet忙碌,造成程式response time太久而當機
#此時程式如果起來,就sleep 0.5~1 小時
currentTime = Time::now
if currentTime.hour == 12
#12:30前程式起來,則延遲1小時才動作
if currentTime.min <= 30
sleep 3600
#12:30後程式起來,則延遲0.5小時才動作
else
sleep 1800
end
end
getLevel
show_hp
get_time_of_next_attack
@attack_number = @driver.find_element(:id, "expeditionpoints_value").text.match(/\d+/).to_s.to_i
@boundroumi_number = @driver.find_element(:id, "dungeonpoints_value").text.match(/\d+/).to_s.to_i
puts "expedition points : #{@attack_number}"
puts "dungeon points : #{@boundroumi_number}"
#puts "arena time : #{@arena_time}"
#puts "cosmo arena time : #{@cosmo_arena_time}"
if @attack_number > 1 and @exp_time == 30 and @hp > 10
exp_attack
end
if @boundroumi_number > 1 and @mpou_time == 30
mpou_attack
end
#if @arena_time == 30 and @hp > 10
# arena_attack
#end
if @cosmo_arena_time == 30
cosmoarena_attack
end
# puts @attack_number
# puts @exp_time
if @hp <= 10 && (@boundroumi_number > 1 || @attack_number > 1)
puts "Needs energy (HP), give him something to eat or I will let him work-fight in dungeon to replace some energy"
work_time_left
if @left_time > 0
puts "still working on, wait for #{@left_time}"
sleep @left_time
else
max_job_per_hour
end
@total_time = 0
end
if @boundroumi_number == 1 && @attack_number == 1 || #level >= 10
@mpou_time-30 == 36000 && @attack_number == 1 #level < 10
work_time_left
if @left_time > 0
puts "still working on, wait for #{@left_time}"
sleep @left_time
else
gladjob_eight
#max_job_per_hour
#puts "max_job_per_hour"
end
@total_time = 0
end
#`killall -9 firefox`
puts "#{@total_time} seconds left to login again..."
sleep @total_time
end
i = 0
loop do
attack
end
# -*- coding: utf-8 -*-
require 'rubygems'
require 'selenium-webdriver'
load 'glad-methods.rb'
if ARGV[0] == "1"
puts "login1"
login1
elsif ARGV[0] == "5"
puts "login5"
login5
elsif ARGV[0] == "7"
puts "login7"
login7
end
def attack
#為了防備中午12:00~13:00公司internet忙碌,造成程式response time太久而當機
#此時程式如果起來,就sleep 0.5~1 小時
currentTime = Time::now
if currentTime.hour == 12
#12:30前程式起來,則延遲1小時才動作
if currentTime.min <= 30
sleep 3600
#12:30後程式起來,則延遲0.5小時才動作
else
sleep 1800
end
end
getLevel
show_hp
get_time_of_next_attack
@attack_number = @driver.find_element(:id, "expeditionpoints_value").text.match(/\d+/).to_s.to_i
@boundroumi_number = @driver.find_element(:id, "dungeonpoints_value").text.match(/\d+/).to_s.to_i
puts "expedition points : #{@attack_number}"
puts "dungeon points : #{@boundroumi_number}"
#puts "arena time : #{@arena_time}"
#puts "cosmo arena time : #{@cosmo_arena_time}"
if @attack_number > 1 and @exp_time == 30 and @hp > 10
exp_attack
end
if @boundroumi_number > 1 and @mpou_time == 30
mpou_attack
end
#if @arena_time == 30 and @hp > 10
# arena_attack
#end
if @cosmo_arena_time == 30
cosmoarena_attack
end
# puts @attack_number
# puts @exp_time
if @hp <= 10 && (@boundroumi_number > 1 || @attack_number > 1)
puts "Needs energy (HP), give him something to eat or I will let him work-fight in dungeon to replace some energy"
work_time_left
if @left_time > 0
puts "still working on, wait for #{@left_time}"
sleep @left_time
else
max_job_per_hour
end
@total_time = 0
end
if @boundroumi_number == 1 && @attack_number == 1 || #level >= 10
@mpou_time-30 == 36000 && @attack_number == 1 #level < 10
work_time_left
if @left_time > 0
puts "still working on, wait for #{@left_time}"
sleep @left_time
else
gladjob_eight
#max_job_per_hour
#puts "max_job_per_hour"
end
@total_time = 0
end
#`killall -9 firefox`
puts "#{@total_time} seconds left to login again..."
sleep @total_time
end
i = 0
loop do
attack
end
glad-methods.rb# -*- coding: utf-8 -*- @total_time = 0 def login @driver = Selenium::WebDriver.for :firefox @driver.get "http://s1.gladiatus.gr/game/" @driver.find_element(:id, "login_username").click @driver.find_element(:id, "login_username").clear @driver.find_element(:id, "login_username").send_keys "xxx" @driver.find_element(:id, "login_password").clear @driver.find_element(:id, "login_password").send_keys "yyy" @driver.find_element(:id, "loginsubmit").click end def login1 @driver = Selenium::WebDriver.for :firefox @wait = Selenium::WebDriver::Wait.new(:timeout => 10) @driver.get "http://s1.gladiatus.tw/game/" @driver.find_element(:id, "login_username").click @driver.find_element(:id, "login_username").clear @driver.find_element(:id, "login_username").send_keys "xxx" @driver.find_element(:id, "login_password").clear @driver.find_element(:id, "login_password").send_keys "yyy" @driver.find_element(:id, "loginsubmit").click end def login5 @driver = Selenium::WebDriver.for :firefox @wait = Selenium::WebDriver::Wait.new(:timeout => 10) @driver.get "http://s5.gladiatus.tw/game/" @driver.find_element(:id, "login_username").click @driver.find_element(:id, "login_username").clear @driver.find_element(:id, "login_username").send_keys "xxx" @driver.find_element(:id, "login_password").clear @driver.find_element(:id, "login_password").send_keys "yyy" @driver.find_element(:id, "loginsubmit").click end def login7 @driver = Selenium::WebDriver.for :firefox @wait = Selenium::WebDriver::Wait.new(:timeout => 10) @driver.get "http://s7.gladiatus.tw/game/" @driver.find_element(:id, "login_username").click @driver.find_element(:id, "login_username").clear @driver.find_element(:id, "login_username").send_keys "xxx" @driver.find_element(:id, "login_password").clear @driver.find_element(:id, "login_password").send_keys "yyy" @driver.find_element(:id, "loginsubmit").click end def get_time_of_next_attack #@driver.find_element(:link, "神諭").click #@driver.find_element(:link, "概覽").click # From Attacks cooldown = @wait.until {@driver.find_elements(:id, "cooldown_bar_text_expedition")} time = cooldown.first.text hours = time.match(/\d+/) minutes = time.match(/:\d+/)#.gsub(":", "") seconds = time.match(/:\d+:\d+/) hours = hours.to_s.to_i minutes = minutes.to_s.slice(1..3).to_i seconds = seconds.to_s.slice(4..5).to_i @exp_time = 0 @exp_time = hours*60*60 + minutes * 60 + seconds + 30 if time =~ /-/ work_time_left else puts "Expedition: #{@exp_time-30} second(s) " end # From Mpountroumi cooldown = @wait.until {@driver.find_elements(:id, "cooldown_bar_text_dungeon")} time = cooldown.first.text hours = time.match(/\d+/) minutes = time.match(/:\d+/)#.gsub(":", "") seconds = time.match(/:\d+:\d+/) hours = hours.to_s.to_i minutes = minutes.to_s.slice(1..3).to_i seconds = seconds.to_s.slice(4..5).to_i @mpou_time = 0 @mpou_time = hours*60*60 + minutes * 60 + seconds + 30 if time =~ /-/ work_time_left else puts "Mpountroumi: #{@mpou_time-30} second(s) " end # From Arena #cooldown = @wait.until {@driver.find_elements(:id, "cooldown_bar_text_arena")} #time = cooldown.first.text #hours = time.match(/\d+/) #minutes = time.match(/:\d+/)#.gsub(":", "") #seconds = time.match(/:\d+:\d+/) #hours = hours.to_s.to_i #minutes = minutes.to_s.slice(1..3).to_i #seconds = seconds.to_s.slice(4..5).to_i #@arena_time = 0 #@arena_time = hours*60*60 + minutes * 60 + seconds + 30 #if time =~ /-/ # work_time_left #else # puts "Arena: #{@arena_time-30} second(s)" #end # From Cosmoarena cooldown = @wait.until {@driver.find_elements(:id, "cooldown_bar_text_ct")} time = cooldown.first.text hours = time.match(/\d+/) minutes = time.match(/:\d+/)#.gsub(":", "") seconds = time.match(/:\d+:\d+/) hours = hours.to_s.to_i minutes = minutes.to_s.slice(1..3).to_i seconds = seconds.to_s.slice(4..5).to_i @cosmo_arena_time = 0 @cosmo_arena_time = hours*60*60 + minutes * 60 + seconds + 30 if time =~ /-/ work_time_left else puts "Cosmo Arena: #{@cosmo_arena_time-30} second(s) " end @times = [] @times << @mpou_time @times << @exp_time #@times << @arena_time @times << @cosmo_arena_time @times.sort! @total_time = @times[0] #if @mpou_time < @exp_time # @total_time = @mpou_time #else # @total_time = @exp_time #end #puts "ATTACK!" if @total_time == 30 end def show_hp @hp = @wait.until {@driver.find_element(:id, "header_values_hp_percent").text} @hp = @hp.to_s.gsub("%","").to_i puts "HP: #{@hp}%" if @hp < 10 puts "eat" #eat end end def getLevel level = @wait.until {@driver.find_elements(:class, "headervalue_small")} @charLevel = level[3].text.to_i #array index start from 0, level is the 4th, so the index is 3 puts "" puts "Level = #{@charLevel}" end def exp_attack puts "遠征 attack" if ARGV[1] != nil target = ARGV[1] else target = 2 end @wait.until {@driver.find_element(:class, "cooldown_bar_link")}.click #@wait.until {@driver.find_element(:xpath, "(//button[@value=''])[#{target}]")}.click button = @wait.until {@driver.find_element(:xpath, "(//button[@value=''])[#{target}]")} while button == nil puts "loop for finding 遠征 button" button = @wait.until {@driver.find_element(:xpath, "(//button[@value=''])[#{target}]")} end button.click end def mpou_attack puts "地下城 attack" @wait.until {@driver.find_element(:xpath, "(//a[@class='cooldown_bar_link'])[2]")}.click start_boundroumi = @wait.until {@driver.find_elements(:class, "button1")} #start_boundroumi.first.click if start_boundroumi.first.attribute('value') == "Κανονικό" while start_boundroumi.first == nil start_boundroumi = @driver.find_elements(:class, "button1") puts "loop for fingding 地下城 button1" end start_boundroumi.first.click if start_boundroumi.first.attribute('value') == "平庸級" #@wait.until {@driver.find_elements(:xpath, "(//img[@onclick])")}.first.click onclick = @driver.find_elements(:xpath, "(//img[@onclick])") while onclick == nil puts "loop for finding 地下城 img onclick" onclick = @driver.find_elements(:xpath, "(//img[@onclick])") end onclick.first.click end def arena_attack puts "競技場 attack" if @charLevel < 10 @wait.until {@driver.find_element(:xpath, "(//a[@class='cooldown_bar_link'])[2]")}.click #< level 10 else @wait.until {@driver.find_element(:xpath, "(//a[@class='cooldown_bar_link'])[3]")}.click #>= level 10 end #@driver.find_element(:link, "Αρένα Επαρχιών").click @wait.until {@driver.find_element(:link, "跨域羅馬競技場")}.click @arena_table = [] (2..6).each do |i| @arena_table << [i, @wait.until {@driver.find_element(:xpath, "/html/body/div[2]/div/div[5]/div/div[2]/div[2]/table/tbody/tr[2]/td/div[2]/div/table/tbody/tr[#{i}]/td[2]").text}] #puts #{@arena_table} end #@arena_table.sort_by! { |row| row[1] } @arena_table.sort_by { |row| row[1] } #puts "To mikrotero level einai tis grammis #{@arena_table[0][0] - 1} me level #{@arena_table[0][1]}" puts "To mikrotero level einai tis grammis #{@arena_table[0][0] - 1} me level #{@arena_table[0][1]}" @driver.find_element(:xpath, "/html/body/div[2]/div/div[5]/div/div[2]/div[2]/table/tbody/tr[2]/td/div[2]/div/table/tbody/tr[#{@arena_table[0][0]}]/td[4]/span").click end def cosmoarena_attack puts "特瑪競技場 attack" @wait.until {@driver.find_element(:xpath, "(//a[@class='cooldown_bar_link'])[4]")}.click sleep 2 #@driver.find_element(:link, "Αρένα Κοσμοσυρροής").click @wait.until {@driver.find_element(:link, "跨域特瑪競技場")}.click sleep 2 @cosmo_table = [] (2..6).each do |i| @cosmo_table << [i, @wait.until {@driver.find_element(:xpath, "/html/body/div[2]/div/div[5]/div/div[2]/div[2]/table/tbody/tr[2]/td/div[2]/div/table/tbody/tr[#{i}]/td[2]").text}] end #@cosmo_table.sort_by! { |row| row[1] } @cosmo_table.sort_by { |row| row[1] } puts "To mikrotero level einai tis grammis #{@cosmo_table[0][0] - 1} me level #{@cosmo_table[0][1]}" @driver.find_element(:xpath, "/html/body/div[2]/div/div[5]/div/div[2]/div[2]/table/tbody/tr[2]/td/div[2]/div/table/tbody/tr[#{@cosmo_table[0][0]}]/td[4]/span").click #@driver.find_element(:xpath, "/html/body/div[2]/div/div[5]/div/div[2]/div[2]/table/tbody/tr[2]/td/div[2]/div/table/tbody/tr[3]/td[4]/span").click end def gladjob_one @driver.execute_script("switchMenu(1)") @wait.until {@driver.find_element(:link, "職業仲介所")}.click @wait.until {@driver.find_element(:id, "content")}.click @wait.until {@driver.find_element(:id, "job_row_2")}.click unless @wait.until {@driver.find_elements(:id, "ticker1")}.size == 1 Selenium::WebDriver::Support::Select.new(@driver.find_element(:id, "workTime")).select_by(:text, "1 小時") @wait.until {@driver.find_element(:id, "doWork")}.click end #`killall -9 firefox` puts "sleep 3720 (one hour) for work in 馬廄..." sleep 3720 end def gladjob_eight @driver.execute_script("switchMenu(1)") @wait.until {@driver.find_element(:link, "職業仲介所")}.click @wait.until {@driver.find_element(:id, "content")}.click @wait.until {@driver.find_element(:id, "job_row_2")}.click unless @wait.until {@driver.find_elements(:id, "ticker1")}.size == 1 Selenium::WebDriver::Support::Select.new(@driver.find_element(:id, "workTime")).select_by(:text, "8 小時") @wait.until {@driver.find_element(:id, "doWork")}.click end #`killall -9 firefox` puts "sleep 28830 (eight hours) for work in 馬廄..." sleep 28830 end def show_tagma_enemies login @driver.find_element(:link, "Τάγμα").click @driver.find_element(:id, "war_master_div").click @driver.find_elements(:xpath, "//div[@class='report_statistic']//table//tr").each do |table_line| #puts table_line.find_elements(:xpath, "//td").first.text #first.find_element(:xpath, "//a"). puts table_line.text[0..-3] end end def max_job_per_hour @driver.execute_script("switchMenu(1)") @wait.until {@driver.find_element(:link, "職業仲介所")}.click @wait.until {@driver.find_element(:id, "content")}.click @wait.until {@driver.find_element(:id, "job_row_4")}.click unless @driver.find_elements(:id, "ticker1").size == 1 Selenium::WebDriver::Support::Select.new(@driver.find_element(:id, "workTime")).select_by(:text, "2 小時") @wait.until {@driver.find_element(:id, "doWork")}.click end #`killall -9 firefox` puts "sleep 7200 (two hours) for work as a 屠夫..." sleep 7200 end def work_time_left @driver.execute_script("switchMenu(1)") @wait.until {@driver.find_element(:link, "職業仲介所")}.click left = @wait.until {@driver.find_elements(:id, "ticker1")} if left.first == nil @left_time = 0 else time = left.first.text hours = time.match(/\d+/) minutes = time.match(/:\d+/)#.gsub(":", "") seconds = time.match(/:\d+:\d+/) hours = hours.to_s.to_i minutes = minutes.to_s.slice(1..3).to_i seconds = seconds.to_s.slice(4..5).to_i @left_time = 0 @left_time = hours*60*60 + minutes * 60 + seconds puts "still working, wait for #{time}" sleep @left_time end end def eat @driver.execute_script("switchMenu(1)") @wait.until {@driver.find_element(:link, "概覽")}.click #heals = @wait.until {@driver.find_elements(:xpath,"//img[@src='7263/img/item/7_16.gif']")} heals = @wait.until {@driver.find_elements(:xpath,"//img[contains(@src,'7263/img/item/7_')]")} #puts "heals = #{heals.first.attribute("src")}" gladiator = @wait.until {@driver.find_element(:id,"p8_1_1")} if heals.length > 0 @driver.action.drag_and_drop(heals.first,gladiator).perform show_hp #@hp = @wait.until {@driver.find_element(:id, "header_values_hp_percent").text} #@hp = @hp.to_s.gsub("%","").to_i end end
訂閱:
文章 (Atom)