Save text and output on textbox (Ruby Selenium/Webdriver) - ruby

I want to get a text from an element and then I want to write that text into another element which is available in another window when window switch.
Selenium::WebDriver::Chrome.driver_path="C:/chromedriver.exe"
browser = Selenium::WebDriver.for :chrome
browser.get 'https://docs.google.com/spreadsheets/d/1BJMqNGK1e2j4VjS8K2kS5wloKpEaHu_GTxMl2KueUCM/edit?usp=sharing'
sleep 8
browser.action.send_keys(:arrow_down).perform
browser.action.send_keys(:left_control, 'c').perform
sleep 1
browser.execute_script("window.open('http://10.19.252.220:25780/PortalCDT/')")
browser.window_handles.each do |handle|
browser.switch_to.window handle
end
sleep 5
browser.find_element(:id, "IdClient").click
browser.find_element(:id, "IdClient").send_keys(:left_control, 'v')
browser.find_element(:id, "ConfirmButton").click
puts "Disp. Cash: " + browser.find_element(:id, "ctl00_ContentPlaceHolder1_ucInfoCliente_lblDispCash").text
column4 = browser.find_element(:id, "ctl00_ContentPlaceHolder1_ucInfoCliente_lblDispCash").text
puts "-------------------------------------"
sleep 1
browser.window_handles.each do |handle|
browser.switch_to.window handle
sleep 1
browser.action.send_keys(:arrow_right).perform
browser.action.send_keys("Id Here").perform
browser.action.send_keys(:arrow_right).perform
browser.action.send_keys(:colunmn4).text
browser.window_handles.each do |handle|
browser.switch_to.window handle
sleep 1
browser.action.send_keys(:arrow_down).perform
browser.action.send_keys(:left_control, 'c').perform
end
browser.window_handles.each do |handle|
browser.switch_to.window handle
end
tried to save the text into column4 variable and then I want to write it into a text field which is another window.
Html code to copy text
<span id="ctl00_ContentPlaceHolder1_ucInfoCliente_lblDispRotativo">2870,14</span>
Thanks!

There are plenty of mistake in your program.
1)To pass,control+c, you should pass[:control,"c"], not like (:control, 'c'), The difference here is, your code would pass control and c sequentially but code [:control,'c'] would hold the control key while it presses c. Do you see the difference?
2)Why are you opening a new tab while you intend to open another url? Open another Browser, that would not need your shift in Window.
Since I can't open your second URL, I copy your intended cell from spreadsheet and paste it in Google search textfield.
require 'selenium-webdriver'
driver=Selenium::WebDriver.for :chrome
driver.navigate.to 'https://docs.google.com/spreadsheets/d/1FMOaVoDF3PsXCgqiEQgYWe8CCO7PcDwsqHpEGT2no3I/edit?usp=sharing'
driver.action.send_keys(:arrow_down).perform
driver.action.send_keys([:control, 'c']).perform
driver1=Selenium::WebDriver.for :chrome
driver1.navigate.to("https://www.google.com/")
driver1.action.send_keys([:control, 'v']).perform

Correct answer:
value = browser.find_element('span#ctl00_ContentPlaceHolder1_ucInfoClient_lblDispCash')
value_text = value.text
text_area = browser.find_element('textbox#whatver_id')
text_area.send_keys(value_text, :enter).perform

Related

Ruby is there a way to stop the user from calling a function/procedure through case before they have accessed a different function/procedure?

I have a text file that I want to open first for reading or writing, but want the user to manually enter the text_file name (which opens the file for reading) first like so:
def read_in_albums
puts "Enter file name: "
begin
file_name = gets().chomp
if (file_name == "albums.txt")
puts "File is open"
a_file = File.new("#{file_name}", "r")
puts a_file.gets
finished = true
else
puts "Please re-enter file name: "
end
end until finished
end
From this unfinished code below, selecting 1 would go to the above procedure. I want the user to select 1 first, and if they choose 2 without having gone through read_in_albums they just get some sort of message like "no file selected and sent back to menu screen.
def main()
finished = false
begin
puts("Main Menu:")
puts("1- Read in Album")
puts("2- Display Album Info")
puts("3- Play Album")
puts("4- Update Album")
puts("5- Exit")
choice = read_integer_in_range("Please enter your choice:", 1, 5)
case choice
when 1
read_in_albums
when 2
display_album_info
when 5
finished = true
end
end until finished
end
main()
The only thing I can think of is something like
when 2
if(read_in_albums == true)
display_album_info
and have it return true from read_in_albums.
which I don't want to do as it just goes through read_in_albums again, when I only want it to do that if the user pressed 1.
All of your application's functionality depends on whether the album data has been read. You are no doubt storing this data as an object in memory referenced by some variable.
$album_data = File.read 'album.txt'
You can test whether this data is present in order to determine whether the file data has been read:
if $album_data.nil?
# ask user for album file
else
# show album user interface
end
There is no need for a separate flag. The mere presence of the data in memory serves as a flag already.
You could either set a flag when option 1 was selcted
has_been_read = false
...
when 1
read_in_albums
has_been_read = true
when 2
if has_been_read
display_album_info
else
puts "Select Option 1 first"
end
Or just test if your file name is a valid string.

How can I read the arrow keys in a Ruby curses application?

I have a Ruby curses application in which I'd like to trap for the arrow keys and function keys. The problem is that some keystrokes generate multiple values when using STDIN.getch. When I type a 'regular' key like a-z I get a single value back. When I type a [F]key or arrow key I get three values back.
Is there a gem designed for handling keyboard input or a better way to accomplish reading keystrokes?
#!/usr/bin/ruby
require 'curses'
require 'io/console'
Curses.noecho
Curses.init_screen
main_window = Curses::Window.new(24, 40, 1, 0)
num_keys = 0
loop do
ch = STDIN.getch
num_keys = num_keys + 1
main_window.addstr(' key:' + ch.inspect + ' count:' + num_keys.to_s)
main_window.refresh
break if ch == 'q'
end
Curses.close_screen
Trying enabling the keypad on the window right after you instantiate it.
main_window = Curses::Window.new(24, 40, 1, 0)
main_window.keypad = true
and then instead of using STDIN.getch there's a getch method on the window as well you can use, so try changing
ch = STDIN.getch
to
ch = main_window.getch
now when I run your program, I get
key: 259 count: 1
when I hit the up arrow instead of
key:"\e" count 1 key:"[" count:2 key:"A" count:3

Making a flashing console message with ruby

0.upto(9) do
STDOUT.print "Flash!"
sleep 0.5
STDOUT.print "\b\b\b\b\b\b" # (6 backspaces, the length of "Flash!")
sleep 0.5
end
This code doesn't work. It prints Flash! to the screen, but it doesn't flash. It just stays there, as though the backspaces aren't taking effect. But I do this:
0.upto(9) do
STDOUT.print "Flash!"
sleep 0.5
STDOUT.print "\b\b\b\b\b" # (5 backspaces, the length of "Flash! - 1")
sleep 0.5
end
and it almost works. It prints this: FFFFFFFFFFlash!(after 9 loops) Why do the backspaces stop taking effect when their number is equal to the length of the string they're deleting?
How can I overcome this problem and create a flashing message, only using libraries that are part of rails?
I tried a workaround like this:
0.upto(9) do
STDOUT.print " Flash!"
sleep 0.5
STDOUT.print "\b\b\b\b\b\b"
sleep 0.5
end
(Note the space in " Flash!"), but what happens is the message appears to crawl across the screen! An interesting effect, but not what I want.
I'm using Command Prompt with Ruby and Rails in Windows 7
Typically this would be written something like:
0.upto(9) do
STDOUT.print "\rFlash!"
sleep 0.5
STDOUT.print "\r " # Send return and six spaces
sleep 0.5
end
Back in the days when we'd talk to TTY and dot-matrix printers, we'd rapidly become used to the carriage-control characters, like "\r", "\n", "\t", etc. Today, people rarely do that to start, because they want to use the web, and browsers; Learning to talk to devices comes a lot later.
"\r" means return the carriage to its home position, which, on a type-writer moved the roller all the way to the right so we could start typing on the left margin again. Printers with moving heads reversed that and would move the print-head all the way to the left, but, in either case, printing started on the left-margin again. With the console/telnet/video-TTY, it moves the cursor to the left margin. It's all the same, just different technology.
A little more usable routine would be:
msg = 'Flash!'
10.times do
print "\r#{ msg }"
sleep 0.5
print "\r#{ ' ' * msg.size }" # Send return and however many spaces are needed.
sleep 0.5
end
Change msg to what you want, and the code will automatically use the right number of spaces to overwrite the characters.
Anyway, it looks like backspace (at least in windows) just positions the cursor back, you need/want to overwrite the character with a space at that point (or 6 of them) to "blank" the text out.
Or, you can just use this
def text_flasher(text)
puts "\e[5m#{text}\e[0m"
end
use text_flasher in the console and you'll see the magic :)
Right, based on #rogerdpack 's input I have devised a solution:
def flashing_output(output)
message = output
backspace = "\b"
space = " "
backspace_array = []
space_array = []
length = message.length
length.times do
backspace_array << backspace
space_array << space
end
0.upto(9) do
print message
sleep 0.5
print backspace_array.join.to_s + space_array.join.to_s + backspace_array.join.to_s + backspace_array.join.to_s
sleep 0.5
end
end
flashing_output("Flashing Foobars! (not a euphemism)")

Check if button is pressed or not

I have a Raspberry Pi with a Siri Proxy that is controlling my garage door, the garage door has only one command for open and close. To check if the garage door is opened to not I bought a magnet switch and I builded a flout point button. I already tried
doorstate = `gpio read 5`.chomp #gives value 1 or 0, 1 is opened, 0 is closed
print doorstate
if doorstate == "1"
print "The garage door is already opened.\n"
elsif doorstate == "0"
print "OK, I'll open it for you!\n"
else
print "Error, please open it manually.\n"
end
Can someone please tell me how I can check fi the returned value or string from doorstate = 'gpio read 5' is equal to a string?
I'm guessing here that the result of 'gpio read 5' contains a line ending.
Try chomping it off:
doorstate = `gpio read 5`.chomp
To verify the class of doorstate, insert p doorstate.class at line 2.
You need to change your single quotes (') to backticks (`, the little thing with the tilde on your keyboard). That will execute the command. The rest of your code is fine.

How to set the URL of a link to a variable using WATIR

Using WATIR and Excel, I'd like to take the first row of a table in Excel, visit the URL, then set the 12th link on the page as a variable in the cell next to the cell with the URL, then go to the next line and repeat.
I'm stuck on getting the URL of the 12th link on the page to set as a variable that I can feed into the next cell in Excel. Here's what I have and it's not working.
worksheet = workbook.WorkSheets(1) # get first workbook
#declare test site
test_site = worksheet.Range("a2").text
#open ie
ie = Watir::IE.new
#go to test_site
ie.goto test_site
#find primlink
ie.link(:index, 12).text = "primlink"
puts primlink
Any ideas?
If you want to get URL from the 12th link, why are you using text method? Use href instead text.
#find primlink
primlink = ie.link(:index, 12).href
puts primlink
I didn't want it to click the link, I wanted it to return the URL without visiting the page, but this is what I ended up going with:
#declare test site
test_site = worksheet.Range("a2").text
#open ie
ie = Watir::IE.new
#go to test_site
ie.goto test_site
#find primlink
ie.link(:index, 12).click
#define primlink
primlink = ie.url()
#goback
ie.back()
#find seclink
ie.link(:index, 14).click
#define seclink
seclink = ie.url()
#set primlink and seclink
worksheet.Range("b2").value = primlink
worksheet.Range("c2").value = seclink
Now I just have to figure out how to turn the cell references into relative references and iterate through an entire list or urls, but that's a whole other thread...

Resources