如何查找/查找ID和xpath在每次刷新时都会更改的元素-Selenium WebDriver Java
我正在使用Java开发Selenium Webdriver,但遇到了问题.我在页面上有一个字段,每次加载该页面时,其ID和xpath都会更改.就像,当我手动打开该页面时,我可以看到一些id和xpath,但是当我运行测试时,id,xpath发生了变化.例子,
I am working on selenium webdriver using java, and I am facing a problem. I have a field on a page whose id and xpath changes every time that page is loaded. Like, when I open that page manually, I can see some id and xpath, but when my test run, the id, xpath has changed. Example,
.//*[@id='dp1445259656810']
.//*[@id='dp1445260051638']
.//*[@id='dp1445260078674']
.//*[@id='dp1445260154173']
这些是每次我刷新页面时创建的xpath.在运行测试期间,如何找到/找到这样的元素.任何帮助将不胜感激.
these are the xpaths that are created every time I refresh my page. How can I locate/find such an element during my run test. Any help will be highly appreciated.
下面是该字段的HTML代码.
Below is the HTML code for the field.
<div class="form-group event-date">
<div class="input-group">
<input id="dp1445260154173" class="form-control ng-pristine ng-
untouched ng-valid ng-isolate-scope hasDatepicker"
enter-action="datePickerEnter(event)" allow-empty=""
has-datepicker="" ng-model="eventSeries.newEvent.date"
placeholder="Event Date"/>
<span class="input-group-addon">
<i class="fa fa-calendar"/>
</span>
</div>
</div>
通常,当ID或Class属性是动态的时,您需要使用以下属性来查找它们:其他属性/取决于它们对静态标记的依赖.
Usually when ID or Class attributes are dynamic, you need to look for them using: other attributes/by their dependence to static tags.
以下是在Gmail中查找撰写"按钮的示例.它具有:-动态ID-动态类-一个静态唯一属性
Here is an example of looking for a "Compose" button in Gmail. It has: - Dynamic ID - Dynamic Class - One static unique attribute
这是HTML代码:
<div class="T-I J-J5-Ji T-I-KE L3" tabindex="0" role="button" style="-moz-user-select: none;" gh="cm">COMPOSE</div>
所以我的xpath是:
So my xpath would be:
//div[@gh='cm']
或者假设您正在寻找Gmail上的发送邮件"按钮.它具有:-动态ID-动态类-一个静态唯一属性
Or imagine that you are looking for a "Send message" button on Gmail. It has: - Dynamic ID - Dynamic Class - One static unique attribute
HTML代码:
<div id=":ly" class="T-I J-J5-Ji aoO T-I-atl L3" tabindex="1" role="button" style="-moz-user-select: none;" data-tooltip="Send (Ctrl-Enter)" aria-label="Send (Ctrl-Enter)" data-tooltip-delay="800">Send</div>
此示例使用CSS选择器:
This example uses CSS selector:
[aria-label*='Enter)']
这里的规则是,当动态对象是动态对象时,请使用静态对象作为参考.
the rule here is, when something is dynamic, look for it by using something static as a reference.
在您的情况下,它将是:
In your case it will be:
//div[@class="form-group event-date"]/input
如果您的div类不是动态的,则可以正常工作.
works if your div-class is not dynamic.