【问题标题】:Python BeautifulSoup to scrape tables from a webpagePython BeautifulSoup 从网页中抓取表格
【发布时间】:2015-12-13 11:24:02
【问题描述】:

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

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

【问题讨论】:

  • 那么预期的输出是什么?
  • 我需要表格列中的数据。所有者:TALLINK GRUPP AS;国旗:爱沙尼亚;最后将其全部保存为 .csv 或 .txt 中的表格
  • 简短回答:soup.find_all() 返回一个没有.find() 方法的列表。您应该使用 for 循环。

标签: python web-scraping beautifulsoup


【解决方案1】:

有几点:

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

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

当您执行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 3 的人,请使用 print("no tbody")
猜你喜欢
  • 1970-01-01
  • 2018-04-25
  • 2014-06-20
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
  • 2012-04-22
相关资源
最近更新 更多