NickaBrick
NickaBrick

Reputation: 81

xpath for two attributes

I am having trouble with the syntax for an xpath for two attributes on one element.

Here is my code:

WebElement dlFileBtn = driver.findElement(
   By.xpath("//*[contains(@href='/file/download/id/" + downloadID + "')]" 
          + "/@*[title()='Download file']"));

Here is the HTML for the element:

<a title="Download file" alt="Right-click to download. (Hold-click Mac.)" 
   target="dlfile" data-isimage="false" class="download" 
   href="/file/download/id/1169">Download file</a>

Since there are two buttons with the same href, I need to query them on ID and title. Thanks for the help!

Upvotes: 2

Views: 10100

Answers (3)

Ishita Shah
Ishita Shah

Reputation: 4035

There is no ID available on the element which you have provided,

You can locate element by:

//a[@title='Download file' and @href='/file/download/id/1169']

Target of tag.

Upvotes: 2

Mads Hansen
Mads Hansen

Reputation: 66781

The first predicate with contains() function has an issue.

  • contains() accepts two parameters. The first parameter is the value to be tested, and the second is the value to search for. It should be [contains(@href,'/file/download/id/" + downloadID + "')]
  • or you could just test the entire value with [@href='/file/download/id/" + downloadID + "']

The last part of your XPath has a couple of problems: /@*[title()='Download file']

  • /@* instead of applying another predicate filter to the matched element, you are selecting all of the matched elements attributes and then
  • [title()='Download file'] is a predicate filter that attempts to select only the attribute(s) that have title() equal to "Download file"
  • However, there is no title() node selector or function to filter those attributes

You could use multiple predicates and adjust that last part of the XPath to:

//*[@href='/file/download/id/" + downloadID + "'][@title='Download file']

You can combine those predicate filters and test multiple expressions in the same predicate with and and or operators.

//*[@href='/file/download/id/" + downloadID + "' and @title='Download file']

Upvotes: 4

soccerway
soccerway

Reputation: 12011

Can you check if the below options with cssSelector or xpath works for you, just give a try;

WebElement ele1 = driver.findElement(By.cssSelector("a[id='Id goes here'][title='Download file']"));
WebElement ele1 = driver.findElement(By.xpath("//a[@id='Id goes here'][@title='Download file']"));

Upvotes: 0

Related Questions