使用 Selenium 识别 angular 网站中的元素

Identify an element with in an angular website using 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 相同 - 我已经向您展示了两者的代码,但您甚至可以通过为输入元素指定一个属性来访问它

要确定你必须诱导的元素 for the element_to_be_clickable() and you can use either of the following :

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