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获取Linux系统的各种信息
Jul 10 Python
python自动化测试之setUp与tearDown实例
Sep 28 Python
Python THREADING模块中的JOIN()方法深入理解
Feb 18 Python
Python部署web开发程序的几种方法
May 05 Python
删除DataFrame中值全为NaN或者包含有NaN的列或行方法
Nov 06 Python
Python 的AES加密与解密实现
Jul 09 Python
python 标准差计算的实现(std)
Jul 29 Python
用python wxpy管理微信公众号并利用微信获取自己的开源数据
Jul 30 Python
Python学习笔记之Django创建第一个数据库模型的方法
Aug 07 Python
python enumerate内置函数用法总结
Jan 07 Python
python 错误处理 assert详解
Apr 20 Python
python实现凯撒密码、凯撒加解密算法
Jun 11 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中取得URL的根域名的代码
2011/03/23 PHP
php页面防重复提交方法总结
2013/11/25 PHP
php简单检测404页面的方法示例
2019/08/23 PHP
swoole锁的机制代码实例讲解
2021/03/04 PHP
javascript两种function的定义介绍及区别说明
2013/05/02 Javascript
textarea 控制输入字符字节数(示例代码)
2013/12/27 Javascript
AngularJS 让人爱不释手的八种功能
2016/03/23 Javascript
基于BootStrap环境写jQuery tabs插件
2016/07/12 Javascript
微信小程序 欢迎页面的制作(源码下载)
2017/01/09 Javascript
基于LayUI分页和LayUI laypage分页的使用示例
2017/08/02 Javascript
vuex 的简单使用
2018/03/22 Javascript
浅谈VUE单页应用首屏加载速度优化方案
2018/08/28 Javascript
vue中的适配px2rem示例代码
2018/11/19 Javascript
微信小程序getLocation 需要在app.json中声明permission字段
2020/03/03 Javascript
在Python中使用__slots__方法的详细教程
2015/04/28 Python
Python实现的基数排序算法原理与用法实例分析
2017/11/23 Python
简单了解什么是神经网络
2017/12/23 Python
深入浅析Python中的yield关键字
2018/01/24 Python
python 将数据保存为excel的xls格式(实例讲解)
2018/05/03 Python
python中从str中提取元素到list以及将list转换为str的方法
2018/06/26 Python
Python使用matplotlib实现基础绘图功能示例
2018/07/03 Python
Django模型序列化返回自然主键值示例代码
2019/06/12 Python
python高斯分布概率密度函数的使用详解
2019/07/10 Python
Python 根据日志级别打印不同颜色的日志的方法示例
2019/08/08 Python
使用OpenCV获取图像某点的颜色值,并设置某点的颜色
2020/06/02 Python
pandas 像SQL一样使用WHERE IN查询条件说明
2020/06/05 Python
Python wordcloud库安装方法总结
2020/12/31 Python
详解HTML5中的标签
2015/06/19 HTML / CSS
纽约著名的服装辅料来源:M&J Trimming
2017/07/26 全球购物
教师个人自我评价
2015/03/04 职场文书
2015年三万活动总结
2015/03/25 职场文书
2016学习医德医风心得体会
2016/01/25 职场文书
关于艺术节的开幕致辞
2016/03/04 职场文书
HTML基础-标签分类(闭合标签,空标签,块级元素,行内元素,行级块元素,可替换元素)
2021/03/31 HTML / CSS
HTML5之高度塌陷问题的解决
2022/06/01 HTML / CSS
python manim实现排序算法动画示例
2022/08/14 Python