简体   繁体   中英

HTML parsing with Beautiful soup

This is what my HTML looks like :

<table cellspacing="0" cellpadding="0"  class="list04" style="width:704px;">

    <td class="txt"><img src="img/1001.gif" /></td>
    <td>
    <div>string1</div>
    <div>
    string2</div>
    </td>
    <td><div class="name">string3</div>
    </td>
    <td>
    </td>
    <td></td>
    </tr>
    <tr>
    <td></td>


    <td class="txt"><img src="img/1002.gif" /></td>
    <td>
    <div>string4</div>
    <div>
    string5</div>
    </td>
    <td><div class="name">string6</div>
    </td>
    <td>
    </td>
    <td></td>
    </tr>
    <tr>
    <td></td>

</table>

I want to extract strings ( string1 to string6 ) with Beautiful soup.

Can anyone answer me how to do this?

** there are so many <div> s in the rest of HTML and i don't need them all. I want to extract strings between <td class="txt"> and </td>

If that is in the string html , use

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
print [t.text for t in soup.find("table", {"class": "list04"}).findAll("div")]

which will print out:

[u'string1', u'string2', u'string3', u'string4', u'string5', u'string6']

Try this

from BeautifulSoup import BeautifulSoup 
f = open('a.htm')
soup = BeautifulSoup(f) 
anothersoup = BeautifulSoup(soup.findAll('td', attrs={'class':'txt'}))
list = anothersoup.findAll('div')
print list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM