You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Protractor中按type、value或alt属性定位元素?附实例

Hey there! Let's break down how to handle both of your Protractor element locating scenarios without relying on class names—super straightforward once you know the right selectors to use.


实例1:通过type或value属性定位提交按钮

Your button has both type="submit" and value="Login" attributes, so you can use either (or combine them for extra precision) with CSS selectors or XPath in Protractor. Here are the most common approaches:

方法1:使用CSS选择器(推荐,更简洁)

  • 通过type属性定位:
    const submitButton = element(by.css("button[type='submit']"));
    
  • 通过value属性定位:
    const submitButton = element(by.css("button[value='Login']"));
    
  • 组合两个属性(避免页面上有其他同类型按钮时定位错误):
    const submitButton = element(by.css("button[type='submit'][value='Login']"));
    

方法2:使用XPath

If you prefer XPath syntax, you can write it like this:

const submitButton = element(by.xpath("//button[@type='submit' and @value='Login']"));

Once you've located the element, you can interact with it (like clicking) or check its disabled state just like you would with a class-named element.


实例2:通过alt属性定位图片并验证存在

For the image with alt="Firewall for Code", you'll use similar attribute-based selectors, then validate its presence on the page. Here's how:

步骤1:定位图片元素

Again, CSS selectors are the go-to for simplicity:

const firewallImage = element(by.css("img[alt='Firewall for Code']"));

Or the XPath version:

const firewallImage = element(by.xpath("//img[@alt='Firewall for Code']"));

步骤2:验证元素存在/可见

  • To confirm the image exists in the DOM (even if it's hidden), use isPresent():
    expect(firewallImage.isPresent()).toBe(true);
    
  • If you want to ensure it's actually visible to users (not just loaded in the DOM), use isDisplayed() instead:
    expect(firewallImage.isDisplayed()).toBe(true);
    

That's all! Both methods skip class names entirely and are reliable for these specific attribute-based locators.


内容的提问来源于stack exchange,提问作者UzIT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:16:29