Jsoup library "Did not find balanced marker" error

Using jsoup library I am trying to get the href of an <a> element which contains specified text each time.

Example:

import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements

String url = "https://www.website.com/"
Document currentPageSource

currentPageSource = Jsoup.connect(url).get()
Elements wElements = currentPageSource.select('a[class="class-name"]:contains('+desiredText+')')
if(wElements) {
	// ...
}
  • The variable desiredText is a “global” variable which changes every time that function called.

The problem is when desiredTextcontains single quote character!!! For example, if desiredText is I am here it “works” fine. But if desiredText is I'm here i get this error: Did not find balanced marker at 'I'.

I tried to use desiredText variable with double-quoted, triple-single-quoted or triple-double-quoted but I get the same error.

Any idea how I’ll fix this?

PS: I have to use jsoup because I can see <a> element only through “View Page Source” and not through “Inspector” tool.

Thank you for your time!!!

If the desiredText has a value “I'm here”,

then the following statement

Elements wElements = 
    currentPageSource.select('a[class="class-name"]:contains('+desiredText+')')

will be iterpreted as

    currentPageSource.select('a[class="class-name"]:contains(I'm here)')

The following code fragment

’a[class=“class-name”]:contains(I’

can not be a valid CSS selector. So your code fails.

You should use quotations appropriately.

1 Like

@simos.sigma

You should escape internal quotes. https://github.com/jhy/jsoup/issues/1105

Advice: You should also post questions about libraries on the appropriate forum.

1 Like

Yes, I found this about escape internal quotes but in my case can’t be done!!! I got a working answer at stackoverflow!!!

About the advice… I am really sorry!!! What is the appropriate forum? Obviously I didn’t see it when I was looking in categories.

See my link.

What link?

https://github.com/jhy/jsoup/issues/1105

See it now?

1 Like

I thought you were talking about a sub forum in here, don’t be… Russ Thomas again!!! :slight_smile: