解析HTML表格的最快,最简单,最好的方法?

Zac*_*urt 10 python regex beautifulsoup html-parsing

我想把这个表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())
Run Code Online (Sandbox Code Playgroud)

对我的python代码的改进的评论和建议也欢迎;)

Ste*_*ven 6

对于您的一般问题:从lxml包中尝试lxml.html(将其视为类固醇上的stdlibs xml.etree:相同的xml api,但支持html,xpath,xslt等...)

针对您具体案例的快速示例:

from lxml import html

tree = html.parse('http://www.datamystic.com/timezone/time_zones.html')
table = tree.findall('//table')[1]
data = [
           [td.text_content().strip() for td in row.findall('td')] 
           for row in table.findall('tr')
       ]
Run Code Online (Sandbox Code Playgroud)

这将为您提供一个嵌套列表:每个子列表对应于表中的一行,并包含来自单元格的数据.偷偷插入的广告行尚未过滤掉,但它应该让你顺利.(顺便说一句:lxml很快!)

但是:更具体地说是针对您的特定用例:获取时区数据库信息比获取特定网页有更好的方法(除此之外:请注意,网页实际上提到您不允许复制其内容).甚至现有的库已经使用了这些信息,例如参见python-dateutil.