Convert HTML Table to an Array in Python

本文介绍了一种使用Python从HTML文件中提取表格数据的方法,并将其转换为数组形式,便于进一步的数据处理和分析。作者分享了一个实用的Python脚本,该脚本能够处理带有colspan属性的复杂表格。

It's been quite a long time since my last update.

Currently, I'm working as an intern in one of the GPS. Well, life now is quite different from what was in school.

My first task is to extract some information from hundreds of HTML(4.0) files and fill the useful ones to Excel files.I heard about a famousGoogle's engineering decision:"Python where we can, C++ where we must".So I decided to learn python and adopt it  in this task.

Python 2.7.3 + beautifulSoup 4.1.3

An important procedure is to convert HTML tables to arrays like those in Matlab and OpenCV.

Here's what we've already got.

http://stackoverflow.com/questions/2870667/how-to-convert-an-html-table-to-an-array-in-python

def makelist(table):
  result = []
  allrows = table.findAll('tr')
  for row in allrows:
    result.append([])
    allcols = row.findAll('td')
    for col in allcols:
      thestrings = [unicode(s) for s in col.findAll(text=True)]
      thetext = ''.join(thestrings)
      result[-1].append(thetext)
  return result

For example

<TABLE ID = "3" BORDER=1 WIDTH="100%" COLS=3>
	<CAPTION ALIGN="LEFT">2.2 Prepare</CAPTION>
	<COLGROUP ALIGN="CENTER" SPAN=3>
	<TBODY>
		<TR>
			<TD COLSPAN = "3"><B>Plane Table</B></TD>
		</TR>
		<TR>
			<TH COLSPAN = "3">Prefiltration</TH>
		</TR>
		<TR>
			<TH>blabla<BR>[mm]</TH>
			<TH>blabla<BR>[mm]</TH>
			<TH>blabla<BR>[mm]</TH>
		</TR>
		<TR>
			<TD>2.50</TD>
			<TD>1.00</TD>
			<TD>3.50</TD>
		</TR>
</TABLE>
Each col in result would be 1, 0, 0, 3 using the above python code.However, one might wanna get result like 3, 0, 0, 3(then you can get 0, 3, 3, 0 just replace 'td' with 'th').

The key point to solve this problem is to get the attribute 'colspan'.

Here is the solution:

def makelist(table):
    result = []
    allrows = table.find_all('tr')
    for row in allrows:
        result.append([])
        allcols = row.find_all('td')
        for col in allcols:
            thestrings = [unicode(s) for s in col.find_all(text=True)]
            thetext = ''.join(thestrings)
            result[-1].append(thetext)
            if col.has_attr('colspan'):#if colspan != 0, filling blanks
                colspan = col.attrs['colspan']# or colspan = col['colspan']
                for i in range(int(colspan)-1):
                    result[-1].append(unicode(''))
    return result,len(allrows),int(table['cols'])


If  labels <td> and <th> are mixed in the same row, you can simply change

allcols = row.find_all('td')
to:
allcols = row.find_all(["td","th"])
then a table actually becomes 'one' table. 



### JavaScript 中 `Uncaught (in promise) TypeError: Cannot convert object to primitive value` 的解决方案 该错误通常发生在尝试将对象隐式转换为原始值时失败的情况下。例如,在某些操作中(如拼接字符串、比较运算符等),JavaScript 尝试调用对象的 `toString()` 或 `valueOf()` 方法来获取其原始值表示形式,但如果这些方法未定义或返回 `undefined`,就会触发此错误。 以下是几种可能的原因及其对应的解决方案: #### 原因分析与解决办法 1. **对象被不当使用** 如果在代码中试图将一个复杂对象用于需要原始值的操作,则可能会引发此类错误。可以通过显式指定如何将对象转换为原始值的方式解决问题[^1]。 ```javascript const obj = { toString() { return "custom string"; }, valueOf() { return 42; } }; console.log(obj + ""); // 调用了 obj.toString() console.log(Number(obj)); // 调用了 obj.valueOf() ``` 2. **Promise 链中的数据处理问题** 当 Promise 返回的结果是一个无法正常转换的对象时,也会抛出类似的错误。可以检查 Promise 链中的每一环是否正确地传递了预期的数据类型[^2]。 ```javascript function fetchData() { return new Promise((resolve, reject) => { resolve({ key: "value" }); // 这里假设我们期望的是一个字符串而非对象 }); } fetchData().then(data => { if (typeof data !== "string") { throw new Error("Expected a string but got an object"); } return data.toUpperCase(); // 对象没有toUpperCase方法,因此这里会报错 }).catch(err => { console.error(err.message); }); ``` 3. **Vue 组件内的绑定问题** 在 Vue.js 应用程序中,如果模板部分绑定了不符合预期类型的变量到特定属性上,也可能遇到这种错误。比如表格组件期待数组作为数据源,但实际上提供了其他类型的值[^2]。 ```html <!-- 正确 --> <vxe-table :data="Array.isArray(tableData) ? tableData : []"> </vxe-table> ``` 4. **调试技巧** 使用浏览器开发者工具打断点并逐步执行代码可以帮助定位具体在哪一步发生了异常。另外打印日志也是常用手段之一: ```javascript try { let result = someFunctionThatMightFail(); console.debug('Result:', result); // 查看实际得到的内容是什么样的结构 } catch(e){ console.error('Error occurred:', e.stack || e.message); } ``` 通过以上方式能够有效减少甚至完全规避掉由于类型不匹配而导致的各种运行期错误情况发生。 ```python def example_function(): pass ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值