【发布时间】:2011-06-21 01:37:08
【问题描述】:
我正在尝试将此表http://www.datamystic.com/timezone/time_zones.html 转换为数组格式,以便我可以用它做任何我想做的事情。最好使用 PHP、python 或 JavaScript。
这种问题经常出现,所以我没有寻求解决这个特定问题的帮助,而是寻找有关如何解决所有类似问题的想法。
BeautifulSoup 是首先想到的。 另一种可能性是在 TextMate 中复制/粘贴它,然后运行正则表达式。
你有什么建议?
这是我最终编写的脚本,但正如我所说,我正在寻找更通用的解决方案。
from BeautifulSoup import BeautifulSoup
import urllib2
url = 'http://www.datamystic.com/timezone/time_zones.html';
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html)
tables = soup.findAll("table")
table = tables[1]
rows = table.findAll("tr")
for row in rows:
tds = row.findAll('td')
if(len(tds)==4):
countrycode = tds[1].string
timezone = tds[2].string
if(type(countrycode) is not type(None) and type(timezone) is not type(None)):
print "\'%s\' => \'%s\'," % (countrycode.strip(), timezone.strip())
也欢迎对我的 Python 代码提出改进意见和建议;)
【问题讨论】:
-
BeautifulSoup(或其他解析器)。除了桌子中间那些烦人的广告之外,这几乎是微不足道的。
-
强制链接,因为“html-parsing”和“regex”标签都存在:stackoverflow.com/questions/1732348/…
标签: python regex html-parsing beautifulsoup