使用beautifulsoup,如何在html页面中引用表行

时间:2010-07-30 04:40:53

标签: python beautifulsoup

我有一个看起来像的HTML页面:

    <html>

    ..

    <form post="/products.hmlt" ..>
    ..

    <table ...>
    <tr>...</tr>
    <tr>
       <td>part info</td>
    ..
    </tr>

    </table>

    ..


</form>

..

</html>

我试过了:

form = soup.findAll('form')

table = form.findAll('table')  # table inside form

但是我收到一个错误说:

ResultSet对象没有属性'findAll'

我想对findAll的调用不会返回'beautifulsoup'对象?那我该怎么办?

更新

此页面上有许多表格,但上面显示的标签只有1个表格。

2 个答案:

答案 0 :(得分:3)

findAll返回一个列表,因此首先提取元素:

form = soup.findAll('form')[0]
table = form.findAll('table')[0]  # table inside form

当然,在索引到列表之前,你应该做一些错误检查(即确保它不是空的)。

答案 1 :(得分:2)

我喜欢ars的答案,当然同意需要进行错误检查;
特别是如果要在任何类型的生产代码中使用它。

这可能是一种更详细/更明确的方式来查找您寻找的数据:

from BeautifulSoup import BeautifulSoup as bs
html = '''<html><body><table><tr><td>some text</td></tr></table>
    <form><table><tr><td>some text we care about</td></tr>
    <tr><td>more text we care about</td></tr>
    </table></form></html></body>'''    
soup = bs(html)

for tr in soup.form.findAll('tr'):
    print tr.text
# output:
# some text we care about
# more text we care about

此处参考清理HTML:

>>> print soup.prettify()
<html>
 <body>
  <table>
   <tr>
    <td>
     some text
    </td>
   </tr>
  </table>
  <form>
   <table>
    <tr>
     <td>
      some text we care about
     </td>
    </tr>
    <tr>
     <td>
      more text we care about
     </td>
    </tr>
   </table>
  </form>
 </body>
</html>
相关问题