Reputation: 107
I'm using Selenium to find an web element by css selector. When I hard code it, it works fine like below.
driver.findElement(By.cssSelector("div[aria-label=\"2018-10-17 Shared Google Drive Folder\"]")).getAttribute("data-id");
However, if I want to customize the css selector string based on date like below, it throws a error:
org.openqa.selenium.InvalidSelectorException: invalid selector: An invalid or illegal selector was specified
I print out the cssFormatString and it looks exactly the same as hard coded one above. Could anyone tell me where it went wrong?
// Customized cssFormatString code
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = dateFormat.format(date);
String cssFormatString = "div[aria-label=\\\"" + strDate + " Shared Google Drive Folder\\\"]";
driver.findElement(By.cssSelector(cssFormatString)).getAttribute("data-id");
Upvotes: 2
Views: 875
Reputation: 41
You have to use single quotes instead of double quotes, for example:
String cssFormatString = "div[aria-label='2018-10-17 Shared Google Drive Folder']"
Upvotes: 2
Reputation: 12255
You code not work because you use unnecessary backslashes \
Result of your code is div[aria-label=\"2018-10-18 Shared Google Drive Folder\"]
and because of backslashes you get invalid selector error.
Use one backslash to escape quotes like in code below:
String cssFormatString = "div[aria-label=\"" + strDate + " Shared Google Drive Folder\"]"
Value will be: div[aria-label="2018-10-18 Shared Google Drive Folder"]
Or use single quotes like in @Navarasu answer.
Upvotes: 0
Reputation: 193058
If you want to construct a cssSelector using the value from strDate
and the text Shared Google Drive Folder you can use the following solution:
// Customized cssFormatString code
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = dateFormat.format(date);
driver.findElement(By.cssSelector("div[aria-label^='" + strDate + "'][aria-label$='Shared Google Drive Folder']")).getAttribute("data-id");
Upvotes: 1
Reputation: 8479
Simply use single quotes instead of double quotes, it should work.
String cssFormatString = "div[aria-label='2018-10-17 Shared Google Drive Folder']"
So your string concatination will be simple,
String cssFormatString = "div[aria-label='" + strDate + " Shared Google Drive Folder']"
Upvotes: 6