mike
mike

Reputation: 1137

python html parsing

i need do some html parsing use python .if i have a html file like bellow:

《body》
   《div class="mydiv"》
      《p》i want got it《/p》
      《div》
           《p》 good 《/p》
           《a》 boy  《/a》
      《/div》
   《/div》
《/body》

how can i get the content of 《div class="mydiv"》 ,say , i want got .

      《p》i want got it《/p》
      《div》
           《p》 good 《/p》
           《a》 boy 《/a》
      《/div》

i have try HTMLParser, but i fount it can't. anyway else ? thanks!

Upvotes: 0

Views: 997

Answers (3)

taijirobot2
taijirobot2

Reputation: 376

I would prefer lxml.html.

import lxml.html as H
doc  = H.fromstring(html)
node = doc.xpath("//div[@class='mydiv']")

Upvotes: 1

gennad
gennad

Reputation: 5585

With BeautifulSoup it is as simple as:

from BeautifulSoup import BeautifulSoup
    html = """
      <body>
        <div class="mydiv">
          <p>i want got it</p>
          <div>
            <p> good </p>
            <a> boy  </a>
          </div>
        </div>
      </body>
    """

    soup = BeautifulSoup(html)
    result = soup.findAll('div', {'class': 'mydiv'})
    tag = result[0]
    print tag.contents
    [u'\n', <p>i want got it</p>, u'\n', <div>
    <p> good </p>
    <a> boy  </a>
    </div>, u'\n']

Upvotes: 5

Fred Foo
Fred Foo

Reputation: 363807

Use lxml. Or BeautifulSoup.

Upvotes: 4

Related Questions