1

While using Beautifulsoup and HTMl parser the tags are converted to lower case. But how can we implement while using LXML parser. In the below case i am not able to print the output.But if i parse using html parser. it works fine. can any one please help me out?

html_doc = """
<html><HEAD><title>The Dormouse's story</title></HEAD>

<p class="title"><b>The Dormouse's story</b></p>
<p class="story">...</p>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, "xml")

print soup.head
0

1 Answer 1

5

Don't use the XML parser to parse HTML. HTML is case-insensitive, but XML is not.

You can parse HTML with lxml just fine, just use the HTML modus:

>>> soup = BeautifulSoup(html_doc, "lxml")
>>> soup.head
<head><title>The Dormouse's story</title></head>

if you insist on using the XML parser, you'll have to match the case of the input element:

>>> soup = BeautifulSoup(html_doc, "xml")
>>> soup.head
>>> soup.HEAD
<HEAD><title>The Dormouse's story</title></HEAD>

If you instead want to handle XML and do that case insensitive, stick to the ElementTree API provided by lxml, and do not use BeautifulSoup at all. You'd then have to use a regular expression XPath search:

regexpNS = "http://exslt.org/regular-expressions"
tree.xpath('//*[re:test(., '^head$', 'i')]', namespaces={'re':regexpNS})

which would find all elements with the name head, case insensitively.

2
  • Thanks for the reply. I just gave a sample example which is HTML. Is there any way to implement if the input is real XML.
    – Fla-Hyd
    Feb 21, 2013 at 14:47
  • Finally a solution please share, because is very dificult to deal with Soup Services.
    – Cam T
    Aug 18, 2018 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.