从嵌套的 foreach 循环中读取值。

huangapple go评论147阅读模式
英文:

read the value from nested foreach loop

问题

我有两个字符串数组,我必须在第一个数组元素用于查找网页元素时,从第二个数组中输入值。
以下是示范代码:

    public void isAllTheFieldsDisplayed(String values, String fields) {
        String[] questions = fields.split(",");
        String[] answers = values.split(",");
        for (int i = 0; i < questions.length; i++) {
            String q = questions[i];
            String ans = answers[i];
            find(By.cssSelector("input[id='" + q + "']")).sendKeys(ans);
        }
    }
英文:

I have two String Array, i have to enter the value from the second array while the first array element is used to find webelement.
Here is the sample code:

public void isAllTheFieldsDisplayed(String values, String fields) {
	String[] questions = fields.split(&quot;,&quot;);
	String[] answers = values.split(&quot;,&quot;);
	for(String q : questions) {
	// HERE IS THE PROBLEM - I want only the first answer from the String[] answers. similarly for the second question, i want the second element from the String[] answers.
   // THIS WONT WORK  - for(string ans : answers)
		find(By.cssSelector(&quot;input[id=&#39;&quot;+q+&quot;&#39;]&quot;)).sendKeys(ans);
		
	}
}

答案1

得分: 0

你可能需要检查这两个数组是否包含相同数量的元素。

利用一个简单的整数for循环并从数组中切片元素:-

for(int i=0; i<questions.length; i++) {
  driver.findElement(By.id(questions[i])).sendKeys(answers[i]);
}

我假设find方法是一种对selenium的findElement的封装,由于正在定位id,建议使用By.id吗?

最好在调用sendKeys之前检查是否找到了WebElement

英文:

You probably need to check whether the two arrays contain the same number of elements.

Utilising a simple integer for loop and slice the elements from the arrays:-

for(int i=0; i&lt;questions.length; i++ {
  driver.findElement(By.id(questions[i])).sendKeys(answers[i]);
}

I assume the find method is some sort of wrapper for selenium's findElement
As id is being located suggest using By.id?

Ideally check whether a WebElement is found before calling sendKeys

答案2

得分: 0

这是一个稍微不同的方法。根据您的环境,这可能过于复杂。

由于您的问题和答案之间存在耦合关系,我们希望确保它们正确配对,一旦它们配对,就没有理由再将它们分开分发。

这可以是一个可重用的实用函数,如下所示:

public Map<String, String> csvsToMap(String keyCsv, String valueCsv) {
    String[] questions = keyCsv.split(",");
    String[] answers = valueCsv.split(",");

    // 这也可以是类似于"questions.length >= answers.length"的条件,这样如果问题多于答案,多余的部分将被忽略而不是失败...
    if (questions.length != answers.length) { // 快速失败,显示明确错误
        throw new RuntimeException("问题和答案的数量不同");
    }

    Map<String, String> map = new HashMap<>();

    for (int i = 0; i < questions.length; i++) {
        map.put(questions[i], answers[i]);
    }

    return map;
}

在数据经过清理和准备后,处理数据会变得更容易:

Map<String, String> preparedQuestions = csvsToMap(values, fields);

for (String aQuestion : preparedQuestions.keySet()) {
    String selector = "input[id='" + aQuestion + "']";
    String answer = preparedQuestions.get(aQuestion);

    driver.findElement(By.id(selector)).sendKeys(answer);
}

或者如果使用Java 8,也可以使用流:

csvsToMap(values, fields).entrySet().stream()
            .forEach(pair -> {
                String selector = "input[id='" + pair.getKey() + "']";
                driver.findElement(By.id(selector)).sendKeys(pair.getValue());
            });

像这样预先在一个函数中准备数据,可以让您避免在其他地方使用索引。如果这是您重复使用的模式,这样的辅助函数就成为一个单一的故障点,您可以测试它,对其进行验证,并确信没有其他几乎相同的代码片段,它们可能具有微小的差异或错误。

请注意,这个辅助函数没有任何副作用,只要提供相同的输入,就会始终得到相同的输出。这使得测试比将webdriver操作嵌入到此任务中要容易得多,因为webdriver具有内置的副作用,可以随时在没有您代码的错误情况下失败。(也就是与浏览器交互)

英文:

Here's a slightly different approach. Which could be overkill depending on your environment.

Because of the coupled relationship of your questions and answers, we want to make sure they get paired correctly, and once they're paired there's no reason to distribute them separately anymore.

This could be a re-usable utility function like so:

public Map&lt;String, String&gt; csvsToMap(String keyCsv, String valueCsv) {
    String[] questions = keyCsv.split(&quot;,&quot;);
    String[] answers = valueCsv.split(&quot;,&quot;);

    // This could also be something like &quot;questions.length &gt;= answers.length&quot; so if there 
    // are more questions than answers the extras would be ignored rather than fail....
    if (questions.length != answers.length) { // fail fast and explicit
        throw new RuntimeException(&quot;Not the same number of questions and answers&quot;);
    }
    
    Map&lt;String, String&gt; map = new HashMap&lt;&gt;();
    
    for (int i = 0; i &lt; questions.length; i++) {
        map.put(questions[i], answers[i]);
    }
    
    return map;
}

After the data has been sanitized and prepared for ingesting, handling it becomes a bit easier:

Map&lt;String, String&gt; preparedQuestions = csvsToMap(values, fields);

for (String aQuestion : preparedQuestions.keySet()) {
    String selector = &quot;input[id=&#39;&quot; + aQuestion + &quot;&#39;]&quot;;
    String answer = preparedQuestions.get(aQuestion);

    driver.findElement(By.id(selector)).sendKeys(answer);
}

Or if java8, streams could be used:

csvsToMap(values, fields).entrySet().stream()
            .forEach(pair -&gt; {
                String selector = &quot;input[id=&#39;&quot; + pair.getKey() + &quot;&#39;]&quot;;
                driver.findElement(By.id(selector)).sendKeys(pair.getValue());
            });

Preparing your data in a function like this ahead of time lets you avoid using indexes altogether elsewhere. If this is a pattern you repeat, a helper function like this becomes a single point of failure, which lets you test it, gain confidence in it, and trust that there aren't other near-identical snippets elsewhere that might have subtle differences or bugs.

Note how this helper function doesn't have any side effects, as long as the same inputs are provided, the same output should always result. This makes it easier to test than it would be having webdriver operations baked into this task, as webdriver has built in side-effects which can fail at any time with no fault to your code. (aka talking to the browser)

答案3

得分: -1

迭代器可能会解决这个问题,但我还没有尝试过。

迭代器 itr = questions.iterator();
迭代器 itrans = answers.iterator();

while (itr.hasNext() && itrans.hasNext())

英文:

Iterator may resolve this, But i haven't tried.

Iterator itr = questions.iterator();
Iterator itrans = answers.iterator();

while( itr.hasNext() && itrans.hasNext())

huangapple
  • 本文由 发表于 2020年10月8日 00:55:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/64248754.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定