简体   繁体   English

如果下拉菜单不是选择元素,如何将Webdriver与C#一起使用,如何通过文本选择下拉项?

[英]Using webdriver with c# how can I select a drop down item by text if the drop down menu is not a select element?

I have the following block of code: 我有以下代码块:

<div id="rtmenu"><span class="rt-combobox"><input name="" type="text" autocomplete="off" label="" placeholder="" class=""><span class="rt-combobox-button" style="-webkit-user-select: none;">▼</span><div class="menu-vertical" role="menu" aria-haspopup="true" style="-webkit-user-select: none; left: 342px; top: 357px; display: none;"><div class="rt-menuitem" role="menuitem" id=":l" style="-webkit-user-select: none;"><div class="rt-menuitem-content">Cars</div></div><div class="rt-menuitem" role="menuitem" id=":m" aria-hidden="false" style="-webkit-user-select: none;"><div class="rt-menuitem-content">Motorcycles</div></div></div></span></div>

What I would like to do is select the menu items "Cars" and "Motorcycles" by their text (or value). 我想做的是通过文本(或值)选择菜单项“汽车”和“摩托车”。 I can get them easily by xpath or by ID but the trouble is that their ID's change frequently and new items are added to the list so that breaks my xpaths too. 我可以通过xpath或ID轻松获得它们,但麻烦的是它们的ID经常更改,并且新项目已添加到列表中,因此也破坏了我的xpath。

I have tried using "select" but this dropdown menu isn't a select menu in the traditional sense. 我尝试使用“选择”,但是此下拉菜单不是传统意义上的选择菜单。

Any help would be very much appreciated. 任何帮助将不胜感激。 Thanks everyone 感谢大家

ps I'm using c# ps我正在使用c#

I'm not familiar with c#, but I can suggest an approach or two. 我对c#不熟悉,但是我可以建议一种或两种方法。

As it is not the select tag, in all cases you must imitate real user's actions, such as click - wait until options list is displyed - find needed option - click on it 因为它不是select标记,所以在所有情况下都必须模仿真实用户的操作,例如单击-等待直到显示选项列表-找到所需的选项-单击它

  1. You can use xpath locator .//div[text()='Cars'] to get the required option directly 您可以使用xpath locator .//div[text()='Cars']直接获取所需的选项
  2. You can iterate through the list of all available options, check if its text equals the needed one and if it is - click the element and break the cycle 您可以遍历所有可用选项的列表,检查其文本是否等于所需的文本,以及是否是-单击该元素并中断循环

You've mentioned that your locators become invalid due to new ID's and items in list, so ypu need to use such locators, that do not depend on ID or indexes in this case. 您已经提到过,由于新的ID和列表中的项,定位器变得无效,因此ypu需要使用此类定位器,在这种情况下,它们不依赖于ID或索引。 BTW, using indexes in xpath is horrible, IMHO 顺便说一句,恕我直言,在xpath中使用索引是可怕的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM