Using BeautifulSoup To Extract Specific TD Table Elements Text?

beautifulsoup, html, python

Solution

This gives you the right list:

>>> pred = lambda tag: tag.parent.find('img') is None
>>> list(filter(pred, soup.find('tbody').find_all('a')))
[<a href="hello.html">127.0.0.1<a></a></a>, <a></a>, <a href="hello.html">192.168.0.1<a></a></a>, <a></a>, <a href="hello.html">255.255.255.0<a></a></a>, <a></a>]

just apply `.text` on the elements of this list.

There are multiple empty `<a></a>` tags in above list because the `<a>` tags in the html are not closed properly. To get rid of them, you may use

pred = lambda tag: tag.parent.find('img') is None and tag.text

and ultimately:

>>> [tag.text for tag in filter(pred, soup.find('tbody').find_all('a'))]
['127.0.0.1', '192.168.0.1', '255.255.255.0']

Problem

I trying to extract IP Addresses from a autogenerated HTML table using the BeautifulSoup library and im having a little trouble. The HTML is structured like so: ``` <html> <body> <table class="mainTable"> <thead> <tr> <th>IP</th> <th>Country</th> </tr> </thead> <tbody> <tr> <td><a href="hello.html">127.0.0.1<a></td> <td><img src="uk.gif" /><a href="uk.com">uk</a></td> </tr> <tr> <td><a href="hello.html">192.168.0.1<a></td> <td><img src="uk.gif" /><a href="us.com">us</a></td> </tr> <tr> <td><a href="hello.html">255.255.255.0<a></td> <td><img src="uk.gif" /><a href="br.com">br</a></td> </tr> </tbody> </table> ``` The small code below extracts the text from the two td rows but i only need the IP data, not the IP and Country data: ``` from bs4 import BeautifulSoup soup = BeautifulSoup(open("data.htm")) table = soup.find('table', {'class': 'mainTable'}) for row in table.findAll("a"): print(row.text) ``` this outputs: ``` 127.0.0.1 uk 192.168.0.1 us 255.255.255.0 br ``` What i need is the IP `table.tbody.tr.td.a` elements text and not the country `table.tbody.tr.td.img.a` elements. Are there any experienced users of BeautifulSoup who would have any inkling on how to to this selection and extraction. Thanks.

Original source