Here is my current xpath code "/html/head/title"
.
But you know, in the real world html environment, the code format usually broken, e.g. <html>
tag is missi开发者_C百科ng could cause an exception. So, I would like to know if there's a safe way to extract the <title>
tag? (something like getElementByTagName)
"//title"
perhaps?
Because of the unruly nature of html markup you should use an html parsing library. You didn't specify a platform or language but there are a number of open source libraries out there.
Actually /html/head/title
should work just fine, even on badly malformed mark-up, assuming:
- there is a title element;
- your HTML parser behaves the same way browser parsers do;
- your HTML parser puts the HTML elements into the null namespace.
You will have to allow for the possibility of there being multiple title elements in invalid HTML, so /html/head/title[1]
is possibly better.
If you can use javascript, you can do it:
document.title
If you have something that an XML parser can parse (which is not the case with most HTML, but needs to be the case to use XPath), then you could use //title
to get the element.
精彩评论