簡體   English   中英

無法使用Java中的Selenium WebDriver選擇按鈕

[英]Unable to select a button using Selenium WebDriver in Java

嘗試使用Selenium WebDriver從網頁的可折疊區域中選擇一個按鈕。 我是WebDriver的新手,在解決如何獲得這個特殊的小怪物方面遇到問題。

    <a href="#" class="btn new-fields-button" data-fields="&lt;div class='contributor-form form-inline form-nested'&gt; 
&lt;select id=&quot;video_item_contributors_attributes_39041920_role&quot; name=&quot;video_item[contributors_attributes]
[39041920][role]&quot;&gt;&lt;option value=&quot;Actor&quot;&gt;Actor&lt;/option&gt; &lt;option 
value=&quot;Director&quot;&gt;Director&lt;/option&gt; &lt;option value=&quot;Writer&quot;&gt;Writer&lt;/option&gt; 
&lt;option value=&quot;Producer&quot;&gt;Producer&lt;/option&gt;&lt;/select&gt; &lt;input class=&quot;input-small&quot; 
id=&quot;video_item_contributors_attributes_39041920_name&quot; name=&quot;video_item[contributors_attributes][39041920][name]&quot; 
placeholder=&quot;Name&quot; size=&quot;30&quot; type=&quot;text&quot; /&gt; &lt;a class='btn btn-danger delete-nested' 
data-destroy-id='destroy-contributor-toggle-'&gt; &lt;i class='ss-trash'&gt;&lt;/i&gt; &lt;/a&gt; &lt;/div&gt; " 
data-id="39041920"><i class="ss-plus"></i> Add Contributor</a>

這是一段代碼(試圖將其分解為便於閱讀的代碼),描述了需要單擊的按鈕,這些按鈕直接從Chrome的“檢查元素”視圖中復制而來。 有任何想法嗎?

根據給出的信息,您可以像這樣進行xpath搜索:

WebElement button = webDriver.findElement(By.xpath("//a[@data-id='39041920']"));

不知道data-id屬性是否唯一,因為您對問題頁面的了解並不多。

您需要首先確保a元素不在iframe中。 如果是這樣,則必須使用driver.switchTo().frame("frameName")將上下文切換到框架。

然后找到與a元素唯一且一致的東西,以便能夠識別它。 下面是一些您可以使用的xpath定位器示例。

作為參考,請閱讀XPath W3C Recommendation-它提供了使用xpath所需的所有信息。

通過錨文本

By.xpath("//a[text()=' Add Contributor']") 

在xpath中使用class

By.xpath("//a[@class='btn new-fields-button']") 

要進行部分匹配,可以使用contains()

By.xpath("//a[contains(@class,'new-fields-button')]") 

您還可以使用多個選擇器,例如:

By.xpath("//a[contains(@class,'new-fields-button') and contains(text(),'Add Contributor')]") 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM