怎样用python遍历表格中的内容

建设单位项目名称发文号立案号详情
中铁十六局集团有限公司关于中铁十六局集团有限公司朝阳区青年路10号院项目2#住宅楼建设工程规划许可证延期的申请2017规(朝)延字0001号2017分延字0001详情
北京博达顺源天然气有限公司压缩天然气(CNG)加气母站2017规函复市政字0002号2017函市政字0001详情
北京市平谷区教育委员会 北京市平谷区大华山镇大华山村经济合作社教学楼、风雨操场及食堂2017规(平)乡临建字0001号2017分乡建字0001详情
李甫全翻改建住房(灰瓦1)2017规(西)条居字0001号2017分条居字0001详情
北京市花木有限公司上水工程2017规建市政否字0025号2017市政建字0001详情
北京地铁十六号线投资有限责任公司北京地铁十六号线工程 区间工程 月坛南街站、阜外大街~月坛南街区间2017规延市政字0004号2017延市政字0001详情
北京恒城投资发展集团有限公司人才公租房项目2017分复字0001详情
北京房地集团有限公司和平街十四区简易住宅楼改造项目2017规(朝)选字0002号2017分选字0001详情
北京市环亚创业生物工程技术有限责任公司工业用房2017分监字0001详情
北京公共交通控股(集团)有限公司2017规竣市政字0001号2017监市政字0001详情

这是之前写的一个很简单的解析表格的,就是利用普通的遍历。

 #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time    : 4/10/17
@File    : normalForm.py
@Remark  : 普通表解析
"""

class normalForm(object):
    """
    :param: response
    """

    def __init__(self):
        self.item_dict = {
            u"建设单位": "construction_unit",
            u"项目名称": "project_name",
            u"发文号": "issued_number",
            u"立案号": "case_number",
        }

    def parser_item(self, response, table_xpath):
        # 第一行为表头时,匹配表头从第二行开始
        tr_first = 2
        items_list = list()
        trs = response.xpath("{}//tr".format(table_xpath)).extract()
        for r in xrange(tr_first, len(trs) + 1):
            items = list()
            tds = response.xpath("{}//tr[{}]//td".format(table_xpath, r)).extract()
            for d in xrange(1, len(tds) + 1):
                shi_key = ''.join(response.xpath("{}//tr[{}]//td[{}]//text()".format(table_xpath, tr_first - 1, d)).extract()).replace(u'\xa0', '').replace(u'\r', '').replace(u'\t', '').replace(u'\n', '').replace(u' ', '')
                shi_value = ''.join(response.xpath("{}//tr[{}]//td[{}]//text()".format(table_xpath, r, d)).extract()).replace(u'\xa0', '').replace(u'\r', '').replace(u'\t', '').replace(u'\n', '').replace(u' ', '')
                if shi_key in self.item_dict and shi_value != '':
                    # print shi_key, '^^^^^^', shi_value
                    items.append({self.item_dict[shi_key]: shi_value})
            if len(items) > 0:
                items_list.append(items)
        return items_list

if __name__ == '__main__':
    pass
    # response = xxx  # 此处xxx为你的网页response
    # table_xpath = "/table"
    # normalForm().parser_item(response, table_xpath)