我已经成功地达到了使用 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/因此引用了维基百科。
我是一个完全的业余爱好者,如果这是完全错误的解决方法,我深表歉意。提前致谢。