使用Selenium在一个有角度的网站中识别一个元素



我正在尝试自动化Angular应用程序。目前我唯一的缺点是我不想使用Protractor,我想自动使用Selenium/Eclipse。我试过了,但问题是每当我重新运行测试时,定位器都会不断更改。我浏览了一下网络,没有找到具体的解决方案。网站中一个字段的代码段:

<input _ngcontent-wle-c93="" formcontrolname="FirstName" mattooltip="Enter First Name" maxlength="50" matinput="" placeholder="First Name" class="mat-input-element mat-form-field-autofill-control ng-tns-c47-3 ng-pristine ng-invalid ng-touched" cdk-describedby-host="" id="mat-input-0" aria-invalid="true" aria-required="false" aria-describedby="mat-error-0">

id="mat-input-0"不断更改

对于您的元素,您有几个选项可以访问它

<input _ngcontent-wle-c93="" formcontrolname="FirstName" mattooltip="Enter First Name" maxlength="50" matinput="" placeholder="First Name" class="mat-input-element mat-form-field-autofill-control ng-tns-c47-3 ng-pristine ng-invalid ng-touched" cdk-describedby-host="" id="mat-input-0" aria-invalid="true" aria-required="false" aria-describedby="mat-error-0">

让我们逐个

CSS选择器

drive.findElement(By.cssSelector("input[formcontrolname='FirstName'][placeholder='First Name']"));

XPATH

drive.findElement(By.xpath("//input[contains(@placeholder,'First Name')]"));

drive.findElement(By.xpath("//input[contains(@formcontrolname,'FirstName')]"));

或同时使用

drive.findElement(By.xpath("//input[contains(@formcontrolname,'FirstName') and (@placeholder, 'FirstName')]"));

CSS_SELECTOR也是如此-我已经向您展示了两者的代码,但您甚至可以通过为输入元素指定一个属性来访问它

要识别元素,必须诱导WebDriverWait等待element_to_be_clickable(),并且可以使用以下定位器策略之一:

  • 使用java和XPATH:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[contains(@class, 'mat-input-element') and @formcontrolname='FirstName'][@placeholder='First Name']"))).click();
    
  • 使用python和CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.mat-input-element[formcontrolname='FirstName'][placeholder='First Name']"))).click()
    
  • 注意:对于python客户端,您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

最新更新