简体   繁体   中英

Unable to select a button using Selenium WebDriver in Java

Trying to select a button from a collapsible area of a web page using Selenium WebDriver. I'm very new to WebDriver, and am having issues figuring out how to get this particular little monster.

    <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>

That's the section of code (tried to break it up to be readable here) that describes the button that neds to be clicked, copied directly from Chrome's "Inspect Element" view. Any ideas?

Based on the info given, you could do an xpath search like this:

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

No idea, if the data-id attribute is unique or not though, as you don't really tell much about your page in the question.

You need to ensure first that the a element is not within an iframe. If it is, you will have to switch context to the frame using driver.switchTo().frame("frameName") .

Then find something that is unique and consistent with the a element to be able to identify it. Some example xpath locators you can use are below.

For reference, read XPath W3C Recommendation - it provides all the info you will ever need for working with xpaths.

By anchor text

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

Using the class value with xpath

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

To do a partial match, you can use contains()

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

You can also use multiple selectors, such as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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