使用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_SELECTOR

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相同-我已经向您展示了两者的代码,但是即使为输入元素指定一个属性,您也可以访问它

,

要标识必须为element_to_be_clickable()引出WebDriverWait的元素,可以使用以下任一Locator Strategies

  • 使用XPATH

    new WebDriverWait(driver,20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[contains(@class,'mat-input-element') and @formcontrolname='FirstName'][@placeholder='First Name']"))).click();
    
  • 使用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