My question about Selenium's find element by css selector

Carl :

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");
Navarasu :

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']"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111483&siteId=1
Recommended