Python实现简单HTML表格解析的方法


Posted in Python onJune 15, 2015

本文实例讲述了Python实现简单HTML表格解析的方法。分享给大家供大家参考。具体分析如下:

这里依赖libxml2dom,确保首先安装!导入到你的脚步并调用parse_tables() 函数。

1. source = a string containing the source code you can pass in just the table or the entire page code

2. headers = a list of ints OR a list of strings
If the headers are ints this is for tables with no header, just list the 0 based index of the rows in which you want to extract data.
If the headers are strings this is for tables with header columns (with the tags) it will pull the information from the specified columns

3. The 0 based index of the table in the source code. If there are multiple tables and the table you want to parse is the third table in the code then pass in the number 2 here

It will return a list of lists. each inner list will contain the parsed information.

具体代码如下:

#The goal of table parser is to get specific information from specific
#columns in a table.
#Input: source code from a typical website
#Arguments: a list of headers the user wants to return
#Output: A list of lists of the data in each row
import libxml2dom
def parse_tables(source, headers, table_index):
  """parse_tables(string source, list headers, table_index)
    headers may be a list of strings if the table has headers defined or
    headers may be a list of ints if no headers defined this will get data
    from the rows index.
    This method returns a list of lists
    """
  #Determine if the headers list is strings or ints and make sure they
  #are all the same type
  j = 0
  print 'Printing headers: ',headers
  #route to the correct function
  #if the header type is int
  if type(headers[0]) == type(1):
    #run no_header function
    return no_header(source, headers, table_index)
  #if the header type is string
  elif type(headers[0]) == type('a'):
    #run the header_given function
    return header_given(source, headers, table_index)
  else:
    #return none if the headers aren't correct
    return None
#This function takes in the source code of the whole page a string list of
#headers and the index number of the table on the page. It returns a list of
#lists with the scraped information
def header_given(source, headers, table_index):
  #initiate a list to hole the return list
  return_list = []
  #initiate a list to hold the index numbers of the data in the rows
  header_index = []
  #get a document object out of the source code
  doc = libxml2dom.parseString(source,html=1)
  #get the tables from the document
  tables = doc.getElementsByTagName('table')
  try:
    #try to get focue on the desired table
    main_table = tables[table_index]
  except:
    #if the table doesn't exits then return an error
    return ['The table index was not found']
  #get a list of headers in the table
  table_headers = main_table.getElementsByTagName('th')
  #need a sentry value for the header loop
  loop_sentry = 0
  #loop through each header looking for matches
  for header in table_headers:
    #if the header is in the desired headers list 
    if header.textContent in headers:
      #add it to the header_index
      header_index.append(loop_sentry)
    #add one to the loop_sentry
    loop_sentry+=1
  #get the rows from the table
  rows = main_table.getElementsByTagName('tr')
  #sentry value detecting if the first row is being viewed
  row_sentry = 0
  #loop through the rows in the table, skipping the first row
  for row in rows:
    #if row_sentry is 0 this is our first row
    if row_sentry == 0:
      #make the row_sentry not 0
      row_sentry = 1337
      continue
    #get all cells from the current row
    cells = row.getElementsByTagName('td')
    #initiate a list to append into the return_list
    cell_list = []
    #iterate through all of the header index's
    for i in header_index:
      #append the cells text content to the cell_list
      cell_list.append(cells[i].textContent)
    #append the cell_list to the return_list
    return_list.append(cell_list)
  #return the return_list
  return return_list
#This function takes in the source code of the whole page an int list of
#headers indicating the index number of the needed item and the index number
#of the table on the page. It returns a list of lists with the scraped info
def no_header(source, headers, table_index):
  #initiate a list to hold the return list
  return_list = []
  #get a document object out of the source code
  doc = libxml2dom.parseString(source, html=1)
  #get the tables from document
  tables = doc.getElementsByTagName('table')
  try:
    #Try to get focus on the desired table
    main_table = tables[table_index]
  except:
    #if the table doesn't exits then return an error
    return ['The table index was not found']
  #get all of the rows out of the main_table
  rows = main_table.getElementsByTagName('tr')
  #loop through each row
  for row in rows:
    #get all cells from the current row
    cells = row.getElementsByTagName('td')
    #initiate a list to append into the return_list
    cell_list = []
    #loop through the list of desired headers
    for i in headers:
      try:
        #try to add text from the cell into the cell_list
        cell_list.append(cells[i].textContent)
      except:
        #if there is an error usually an index error just continue
        continue
    #append the data scraped into the return_list    
    return_list.append(cell_list)
  #return the return list
  return return_list

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
python解析文件示例
Jan 23 Python
Python输出由1,2,3,4组成的互不相同且无重复的三位数
Feb 01 Python
实例讲解Python中整数的最大值输出
Mar 17 Python
Django中reverse反转并且传递参数的方法
Aug 06 Python
解决在pycharm运行代码,调用CMD窗口的命令运行显示乱码问题
Aug 23 Python
python实现画出e指数函数的图像
Nov 21 Python
python读取raw binary图片并提取统计信息的实例
Jan 09 Python
Python request操作步骤及代码实例
Apr 13 Python
python实现将中文日期转换为数字日期
Jul 14 Python
详解PyQt5中textBrowser显示print语句输出的简单方法
Aug 07 Python
Python pysnmp使用方法及代码实例
Aug 24 Python
Python使用Opencv打开笔记本电脑摄像头报错解问题及解决
Jun 21 Python
Python判断Abundant Number的方法
Jun 15 #Python
Python计算一个文件里字数的方法
Jun 15 #Python
Python素数检测实例分析
Jun 15 #Python
Python计算三维矢量幅度的方法
Jun 15 #Python
Python栈类实例分析
Jun 15 #Python
Python实现股市信息下载的方法
Jun 15 #Python
给Python入门者的一些编程建议
Jun 15 #Python
You might like
高亮度显示php源代码
2006/10/09 PHP
smarty实例教程
2006/11/19 PHP
php将字符串随机分割成不同长度数组的方法
2015/06/01 PHP
php 截取utf-8格式的字符串实例代码
2016/10/30 PHP
PHP实现用户登录的案例代码
2018/05/10 PHP
php新建文件的方法实例
2019/09/26 PHP
php并发加锁问题分析与设计代码实例讲解
2021/02/26 PHP
PHP实现chrome表单请求数据转换为接口使用的json数据
2021/03/04 PHP
JS 精确统计网站访问量的实例代码
2013/07/05 Javascript
jquery submit ie6下失效的原因分析及解决方法
2013/11/15 Javascript
两个select多选模式的选项相互移动(示例代码)
2014/01/11 Javascript
Bootstrap入门书籍之(一)排版
2016/02/17 Javascript
JavaScript中关键字 in 的使用方法详解
2016/10/17 Javascript
JavaScript实现实时更新系统时间的实例代码
2017/04/04 Javascript
利用Node.js检测端口是否被占用的方法
2017/12/07 Javascript
基于Vue+ElementUI的省市区地址选择通用组件
2019/11/20 Javascript
JavaScript实现简单计算器功能
2019/12/19 Javascript
element-ui点击查看大图的方法示例
2020/12/14 Javascript
SpringBoot+Vue 前后端合并部署的配置方法
2020/12/30 Vue.js
html5以及jQuery实现本地图片上传前的预览代码实例讲解
2021/03/01 jQuery
Python实现简单的文件传输与MySQL备份的脚本分享
2016/01/03 Python
Python multiprocess pool模块报错pickling error问题解决方法分析
2019/03/20 Python
执行Python程序时模块报错问题
2020/03/26 Python
Python基于codecs模块实现文件读写案例解析
2020/05/11 Python
HTML5进阶段内联标签汇总(小篇)
2016/07/13 HTML / CSS
美国男装连锁零售商:Men’s Wearhouse
2016/10/14 全球购物
lululemon美国官网:瑜伽服+跑步装备
2018/11/16 全球购物
美国二手复古奢侈品包包购物网站:LXRandCo
2019/06/18 全球购物
万豪国际住宅与别墅集团:Homes & Villas by Marriott International
2020/10/08 全球购物
上班打牌检讨书
2014/02/07 职场文书
演讲稿格式范文
2014/05/19 职场文书
廉洁自律演讲稿
2014/05/22 职场文书
三八活动策划方案
2014/08/17 职场文书
工作检讨书怎么写
2015/01/23 职场文书
介绍信的写法
2015/01/31 职场文书
公司行政助理岗位职责
2015/04/11 职场文书