Protractor技术问题:仅知图片路径时如何定位元素并验证按钮功能
Got it, let's figure out how to target this image button since it doesn't have a class or ID to rely on. We can use either its alt attribute or src attribute—here are the most reliable approaches:
1. Use the alt Attribute (Recommended)
The alt text is built for accessibility and is usually stable (unlikely to change when the app gets updated). This makes it the best choice for locating the element consistently.
CSS Selector:
const appStoreButton = element(by.css('img[alt="App Store"]'));
XPath Selector:
const appStoreButton = element(by.xpath('//img[@alt="App Store"]'));
2. Use the src Attribute (Fallback Option)
The src path includes a long hash string, which might change when the app's assets are redeployed. If you need to use src, opt for a partial match instead of the full path to avoid broken locators later.
Partial Match with CSS Selector:
// Matches any img whose src contains the base path of the button image const appStoreButton = element(by.css('img[src*="/assets/ap-store-button"]'));
Partial Match with XPath:
const appStoreButton = element(by.xpath('//img[contains(@src, "/assets/ap-store-button")]'));
Full Match (Not Recommended):
Only use this if you're 100% certain the full src path won't change—this is risky because the hash in the filename is likely auto-generated and will update with deployments:
const appStoreButton = element(by.css('img[src="/assets/ap-store-button-f07ba2aa12bbdb0f4830b8a0f12f007a08151bd490498031e6b61092f51f9c56.png"]'));
Quick Tip to Verify the Button Function
Once you've located the element, you can test its functionality like this:
// Click the button appStoreButton.click(); // Verify the expected behavior (e.g., redirect to App Store) expect(browser.getCurrentUrl()).toContain('apple.com/app-store');
内容的提问来源于stack exchange,提问作者Saqib Tanvir

