我已经编写了一个Java类(CustomerHistoryMapping),其中包含一个HashMap(String,WebElement),如下面的代码所示(代码的第一部分)
我的总体目标是能够使用给定的WebElement,具体取决于我传递给HashMap类的字符串。

package com.xxxxx.data;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import java.util.HashMap;
import java.util.Map;

public class CustomerHistoryMapping {

  @FindBy(xpath = "(//td/span[text()='Preferred Name']/../following-sibling::td[3]/span/span)[1]")
  public WebElement txaNewPreferredNameValue;

  @FindBy(xpath = "(//td/span[text()='Mobile']/../following-sibling::td[3]/span/span)[1]")
  public WebElement txaNewMobileValue;

  @FindBy(xpath = "(//td/span[text()='Email']/../following-sibling::td[3]/span/span)[1]")
  public WebElement txaNewEmailValue;

  @FindBy(xpath = "(//td/span[text()='Mailing Street']/../following-sibling::td[3]/span/span)[1]")
  public WebElement txaNewMailingStreetValue;

  @FindBy(xpath = "(//td/span[text()='Mailing City']/../following-sibling::td[3]/span/span)[1]")
  public WebElement txaNewMailingCityValue;

  @FindBy(xpath = "(//td/span[text()='Mailing Zip/Postal Code']/../following-sibling::td[3]/span/span)[1]")
  public WebElement txaNewMailingPostCodeValue;

  @FindBy(xpath = "(//td/span[text()='Mailing State/Province']/../following-sibling::td[3]/span/span)[1]")
  public WebElement txaNewMailingStateValue;

   Map<String, WebElement> mapping = new HashMap<String, WebElement>();

  public CustomerHistoryMapping() {
    mapping.put("preferredName", txaNewPreferredNameValue);
    mapping.put("mobile", txaNewMobileValue);
    mapping.put("email", txaNewEmailValue);
    mapping.put("address", txaNewMailingStreetValue);
    mapping.put("city", txaNewMailingCityValue);
    mapping.put("postcode", txaNewMailingPostCodeValue);
    mapping.put("state",txaNewMailingStateValue);
  }

  public WebElement getValue(String mapKey) {
    return mapping.get(mapKey);
  }

}



但是,当我调用getValue(“ preferredName”)-(请参阅第二段代码)并检查日志时,将显示以下内容:

Str是:preferredName,而ele是:null

      objCustomerHistoryMapping = new CustomerHistoryMapping();
      WebElement ele = objCustomerHistoryMapping.getValue("preferredName");
      logger.info("Str is: preferredName, And ele is: " + ele);



因此HashMap中的WebElement不会被撤回-为什么有任何想法?

最佳答案

您应该添加PageFactory.initElements(...)以便使用页面上的元素初始化字段。您可以将其添加为构造函数的最后一行。

除非您已使用initelements,否则所有字段都将引用null

关于java - 传递字符串时,Selenium Hashmap(String,WebElement)不返回WebElement,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60619896/

10-11 00:01