Python BeautifulSoup 从网页中抓取表格

标签 python web-scraping beautifulsoup

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

我试图通过 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
.....

关于Python BeautifulSoup 从网页中抓取表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34250552/

相关文章:

python - 如何在 Robot Framework- SeleniumLibrary 中获取多个元素并打印?

c# - 使用 HTML Agility Pack 获取图像旁边的文本?

pandas - 使用 beautifulsoup 将 selenium html 表放入 pandas 数据框中

python - 减去,除非为负然后返回 0

python - pip Python 3 权限错误

javascript - 在不打开浏览器的情况下读取 selenium 中的 javascript 代码

python - 如何使用 python 从公共(public)谷歌表中获取数据?

python - Python 前标签之间的解析

python - BeautifulSoup : get picture size from html

python - 使用源代码不洁的 BeautifulSoup 从 HTML 表格中提取链接