0

我已经成功地达到了使用 BeautifulSoup 从 url 中提取表格的地步。此时我想将输出格式化为表格,以便在 GeekTool 中使用它。

from bs4 import BeautifulSoup
import urllib2
wiki = "https://www.google.com/maps/place?q=type:transit_station:%22145+St%22&ftid=0x89c2f67c67a250f9:0x92d51daa07480dd1"
header = {'User-Agent': 'Mozilla/5.0'} #Needed to prevent 403 error on Wikipedia
req = urllib2.Request(wiki,headers=header)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)

desination = ""
eta = ""
table = soup.find("table", { "class" : "pprtjt" })


for row in table.findAll("tr"):
    for cell in row.findAll("td"):
       print cell.findAll(text=True)

输出以下内容:

[u'   C to 168 St  ']
[u'2 min']
[u'   D to Norwood - 205 St  ']
[u'4 min']
[u'   A to Ozone Park - Lefferts Blvd  ']
[u'4 min']
[u'   A to Inwood - 207 St  ']
[u'5 min']
[u'   D to Coney Island - Stillwell Av  ']
[u'10 min']
[u'   C to 168 St  ']
[u'15 min']
[u'   D to Norwood - 205 St  ']
[u'19 min']
[u'   A to Far Rockaway - Mott Av  ']
[u'19 min']
[u'   A to Inwood - 207 St  ']
[u'20 min']

因此,第一行是第一列的第一行,第二行是 to 列的第一行,依此类推,例如:

C to 168 St                 | 2 min
D to Norwood - 205 St       | 4 min
A to Ozone Park - Lefferts Blvd | 4 min
A to Inwood - 207 St        | 5 min
D to Coney Island - Stillwell Av    | 10 min
C to 168 St                 | 15 min
D to Norwood - 205 St       | 19 min
A to Far Rockaway - Mott Av         | 19 min
A to Inwood - 207 St        | 20 min

理想情况下,我希望它打印为表格,然后在 GeekTool 中使用整个想法。我的代码的基础来自这里:http ://adesquared.wordpress.com/2013/06/16/using-python-beautifulsoup-to-scrape-a-wikipedia-table/因此引用了维基百科。

我是一个完全的业余爱好者,如果这是完全错误的解决方法,我深表歉意。提前致谢。

4

2 回答 2

0

查看 termsql,它是一个用于类似目的的工具,虽然我不确定我是否完全理解您的输出,但您可能需要进一步简化它。

手册: http ://tobimensch.github.io/termsql/

项目: https ://github.com/tobimensch/termsql

对您来说有趣的可能是 --line-as-column 选项。

于 2014-12-03T01:27:16.110 回答
0

我认为你的最后一个双循环应该是这样的:

for row in table.findAll("tr"):
    rowText = []
    for cell in row.findAll("td"):
        # Append every cell in this row
        rowText.append(cell.findAll(text=True)[0])
    # print the row joining the cells with '|'
    print ' | '.join(rowText)
于 2014-03-03T14:45:35.937 回答