Skip to main content
 首页 » 编程设计

Python BeautifulSoup 从网页中抓取表格

2024年10月24日12arxive

我正在尝试从具有船舶数据库的网站收集信息。

我试图通过 BeautifulSoup 获取信息。但目前它似乎没有用。我尝试在网上搜索并尝试不同的解决方案,但未能使代码正常工作。

我想知道我必须改变 table = soup.find_all("table", { "class": "table1"}) --- 一行有 5 个 class='table1' 的表,但我的代码只找到 1。

我必须为表格创建一个循环吗?当我尝试这个时,我无法让它工作。还有下一行 table_body = table.find('tbody') 它给出了一个错误:

AttributeError: 'ResultSet' object has no attribute 'find' 

这应该是BeautifulSoup的源代码,那个ResultSet子类列表和我的代码之间的冲突。我是否必须遍历该列表?

from urllib import urlopen 
 
shipUrl = 'http://www.veristar.com/portal/veristarinfo/generalinfo/registers/seaGoingShips?portal:componentId=p_efff31ac-af4c-4e89-83bc-55e6d477d131&interactionstate=JBPNS_rO0ABXdRAAZudW1iZXIAAAABAAYwODkxME0AFGphdmF4LnBvcnRsZXQuYWN0aW9uAAAAAQAYc2hpcFNlYXJjaFJlc3VsdHNTZXRTaGlwAAdfX0VPRl9f&portal:type=action&portal:isSecure=false' 
shipPage = urlopen(shipUrl) 
 
from bs4 import BeautifulSoup 
soup = BeautifulSoup(shipPage) 
table = soup.find_all("table", { "class" : "table1" }) 
print table 
table_body = table.find('tbody') 
rows = table_body.find_all('tr') 
for tr in rows: 
    cols = tr.find_all('td') 
    for td in cols: 
        print td 
    print 

请您参考如下方法:

一些事情:

正如 Kevin 提到的,您需要使用 for 循环来遍历 find_all 返回的列表。

并非所有表都有 tbody,因此您必须将 find 的结果包装在 try block 中。

当您执行 print 时,您希望使用 .text 方法,以便打印文本值而不是标签本身。

修改后的代码:

shipUrl = 'http://www.veristar.com/portal/veristarinfo/generalinfo/registers/seaGoingShips?portal:componentId=p_efff31ac-af4c-4e89-83bc-55e6d477d131&interactionstate=JBPNS_rO0ABXdRAAZudW1iZXIAAAABAAYwODkxME0AFGphdmF4LnBvcnRsZXQuYWN0aW9uAAAAAQAYc2hpcFNlYXJjaFJlc3VsdHNTZXRTaGlwAAdfX0VPRl9f&portal:type=action&portal:isSecure=false' 
shipPage = urlopen(shipUrl) 
 
soup = BeautifulSoup(shipPage) 
table = soup.find_all("table", { "class" : "table1" }) 
for mytable in table: 
    table_body = mytable.find('tbody') 
    try: 
        rows = table_body.find_all('tr') 
        for tr in rows: 
            cols = tr.find_all('td') 
            for td in cols: 
                print td.text 
    except: 
        print "no tbody" 

产生以下输出:

Register Number: 
08910M 
IMO Number: 
9365398 
Ship Name: 
SUPERSTAR 
Call Sign: 
ESIY 
.....