嗨,我正在用Watir编写一个自动化测试脚本。我试图将一个字符串附加到文本字段中的现有字符串中。我想出了如何用这一行代码追加到文本字段的末尾:
browser.text_field(:id => "custom-preview-text").append "Hello World"如何更改这一行,以便在文本字段中的特定字符串之后追加此文本?
发布于 2013-10-31 19:13:02
以下是实现这一目标的一种方法:
require 'watir-webdriver'
b = Watir::Browser.new
b.goto 'https://www.google.co.in/search?output=search&sclient=psy-ab&q=gdg&btnK='
elem = b.text_field(:id => "gbqfq")
val = elem.value
elem.clear
elem.send_keys val + "Good bye!"
puts elem.value
# >> gdgGood bye!发布于 2013-10-31 19:26:32
如果您想在特定字符串之后插入文本,我认为您必须获得文本字段的字符串,使用Ruby确定新字符串,然后使用新字符串输入文本字段。
您可以使用gsub在字符串的某一部分之前或之后插入文本。例如:
original_text = 'word1 word2 word3'
# Insert text before word2
p original_text.sub(/(?=word2)/, 'insertion ')
#=> "word1 insertion word2 word3"
# Insert text after word2
p original_text.sub(/(?<=word2)/, ' insertion')
#=> "word1 word2 insertion word3"在文本字段中插入新字符串如下所示:
# Get the current text field value
text_field = browser.text_field
original_text = text_field.text
# If you want to insert before word 2
new_text = original_text.sub(/(?=word2)/, 'insertion ')
# If you want to insert after word 2
new_text = original_text.sub(/(?<=word2)/, ' insertion')
# Set the text field with the new value
text_field.set(new_text)请注意,此解决方案假定您不介意重新输入现有文本(即没有javascript会触发和搞乱您的测试)。
https://stackoverflow.com/questions/19713672
复制相似问题