1

Taking the below html snippet as example:

>>>soup
<table>
<tr><td class="abc">This is ABC</td>
</tr>
<tr><td class="firstdata"> data1_xxx </td>
</tr>
</table>
<table>
<tr><td class="efg">This is EFG</td>
</tr>
<tr><td class="firstdata"> data1_xxx </td>
</tr>
</table>

If I can only find my desire table by its table data class,

>>>soup.findAll("td",{"class":"abc"})
[<td class="abc">This is ABC</td>]

how can I extract the whole table as below?

<table>
<tr><td class="abc">This is ABC</td>
</tr>
<tr><td class="firstdata"> data1_xxx </td>
</tr>
</table>
alecxe
476k127 gold badges1.1k silver badges1.2k bronze badges
asked May 22, 2014 at 14:25

1 Answer 1

1

Get the td tag's parent using find_parent():

soup.find("td", {"class":"abc"}).find_parent('table')

Demo:

>>> from bs4 import BeautifulSoup
>>> data = """
... <div>
... <table>
... <tr><td class="abc">This is ABC</td>
... </tr>
... <tr><td class="firstdata"> data1_xxx </td>
... </tr>
... </table>
... 
... <table>
... <tr><td class="efg">This is EFG</td>
... </tr>
... <tr><td class="firstdata"> data1_xxx </td>
... </tr>
... </table>
... </div>
... """
>>> soup = BeautifulSoup(data)
>>> print soup.find("td", {"class":"abc"}).find_parent('table')
<table>
<tr><td class="abc">This is ABC</td>
</tr>
<tr><td class="firstdata"> data1_xxx </td>
</tr>
</table>
answered May 22, 2014 at 14:27
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.