【问题标题】:beautiful soup extracting table data美汤提取表数据
【发布时间】:2015-03-18 23:09:12
【问题描述】:

我是 bs4 的菜鸟。我阅读了一些教程并尝试了一些简单的示例。 我想从表中提取数据,但我无法正确完成。

这是 html_source:

<table class="tborder" cellpadding="5" cellspacing="0" border="0" width="100%" align="center" style="margin:5px 0px 5px 0px" id="post45894054">
<tr>
<td>
<div class="alt2" style="margin:5px 0px 5px 0px; padding:5px; border:2px groove">
<div class="smallfont"><em>
<br />
Good news today.
</em></div>
</div>
</td>
</tr>
</table> 

我想提取“今天的好消息”

我尝试了该代码,但没有按预期工作:

from bs4 import BeautifulSoup
import urllib2
import re

base_url = "some url"
html_page = urllib2.urlopen(base_url)

soup = BeautifulSoup(html_page)
print soup
tables = soup.select("table .alt2 .smallfont br")

print tables

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:
    from bs4 import BeautifulSoup
    soup = BeautifulSoup("""<table class="tborder" cellpadding="5" cellspacing="0" border="0" width="100%" align="center" style="margin:5px 0px 5px 0px" id="post45894054">
    <tr>
    <td>
    <div class="alt2" style="margin:5px 0px 5px 0px; padding:5px; border:2px groove">
    <div class="smallfont"><em>
    <br />
    Good news today.
    </em></div>
    </div>
    </td>
    </tr>
    </table> """)
    
    print(soup.find("table",attrs={"class":"tborder"}).text.strip())
    Good news today.
    
    print(soup.find(attrs={"class":"smallfont"}).text.strip())
    Good news today.
    

    【讨论】:

    • @omri_saadon,没办法,有很多不同的方法,只是一对
    • 如何将其更改为 findall?因为当我将其更改为 findall 时,我得到一个异常“'NoneType' 对象不可调用”@Padraic Cunningham
    • 为什么需要 findall?
    • 如果我有很多桌子,而不仅仅是一张
    • 那么首先找到所有表然后遍历该列表并使用我的答案中的两个示例之一来提取文本
    猜你喜欢
    • 2012-08-01
    • 2017-12-11
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2021-12-15
    相关资源
    最近更新 更多