javascript 量角器 - 如何通过自定义(非 HTML)属性定位元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23629606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Protractor - How to locate element by custom (non HTML) attributes?
提问by Madhura Adawadkar
I am using Selenium WebDriver and Protractor to run e2e tests on my angular project. Let's say I have an element like:
我正在使用 Selenium WebDriver 和 Protractor 对我的 angular 项目运行 e2e 测试。假设我有一个元素,如:
<div my-directive my-unique-id="abc123"></div>
How can locate the above element.
I tried with element(by.css('div[my-unique-id="abc123"]'));
, but it gives a NoSuchElementError.
如何定位上述元素。我尝试过element(by.css('div[my-unique-id="abc123"]'));
,但它给出了 NoSuchElementError。
If I try with HTML attributes like, for example, I want to locate:
如果我尝试使用 HTML 属性,例如,我想定位:
<a title="myTitle" href="">Click me</a>
I was able to locate the element correctly using element(by.css('a[title="myTitle"]'))
我能够使用正确定位元素 element(by.css('a[title="myTitle"]'))
How do I locate the element with custom attributes, if it does not have any standard HTML attributes?
如果元素没有任何标准的 HTML 属性,如何定位具有自定义属性的元素?
回答by Andrian Durlestean
Try to use xpath:
尝试使用 xpath:
element(by.xpath('//div[@my-unique-id="abc123"]'))
or only by attribute
或仅按属性
element(by.xpath('//div[@my-unique-id]'))
回答by Sauerkraut
try using:
尝试使用:
element(by.css('[my-unique-id="abc123"]'))
it's easier and more readable than xpath for simple cases.
对于简单的情况,它比 xpath 更容易和更易读。
more about xpath syntax and when it is usefull: http://www.w3schools.com/xml/xml_xpath.asp
有关 xpath 语法以及何时有用的更多信息:http: //www.w3schools.com/xml/xml_xpath.asp