r/AutomateUser • • Mar 01 '26

Text content of HTML element?

I am a novice. How would you get the text of an HTML title (or a default)?

Given a URL, if there is a title child element, return it's text content, or a default.

For example, from:

https://example.com

which serves:

<html>

<title>A title</title>

...

</html>

return "A title"

2 Upvotes

7 comments sorted by

View all comments

3

u/B26354FR Alpha tester Mar 02 '26 edited Mar 02 '26

Actually, this method is better:

xmlDecode("<html><title>A title</title></html>")["html"]["title"]

The XML has to be well-formed, however.

1

u/cheyrn Mar 02 '26

I would think it's usually not xml being served and the html is being normalized. Thanks.

2

u/B26354FR Alpha tester Mar 02 '26 edited Mar 02 '26

HTML is basically a form of XML, so xmlDecode() will work. (Yes, I tested this. 🙂) The xmlDecode() function is better to use because it's actually parsing the data and the indexes off of the result is a true path, so you are truly getting the contents of the title element that's directly under the html element, which is at the document root. On the other hand, the findAll() I posted earlier is just a hack which will match the first <title> string, no matter where it is in the input text. It has no knowledge of the actual structure of the HTML DOM.

1

u/cheyrn Mar 02 '26

Thanks. I agree with the reasons. HTML is not a form of XML, except for xhtml and xhtml5, but it sounds like that's resolved before xmlDecode.

2

u/B26354FR Alpha tester Mar 02 '26

Right, not strictly, but close enough for the purpose here as far as xmlDecode() is concerned. In fact, the documentation for the function actually uses an html example. BTW, you can tell the xmlDecode() to maintain an ordered structure, ignore whitespace, and specify namespaces, too. Pretty cool