python从html表中提取值

时间:2014-02-02 10:42:05

标签: python

我当时认为lxml最适合这个目的,但我愿意接受更好的建议。 基本上我想从一个看起来如下的表中提取值 - (已经在python变量中):

<thead><tr> .... </tr></thead>
<tbody>
<tr><td>col1val1</td><td>col2val1</td></tr>
<tr><td>col1val2</td><td>col2val2</td></tr>
<tr><td>col1val3</td><td>col2val3</td></tr>
</tbody>

现在thead和tbody标签在路上并且不需要,所以不知何故我需要首先切掉这些标签,然后一次遍历所有tr的一行。我需要对每个完整的数据行执行操作(插入到数据库),然后再转到下一行。

我认为前两个答案不起作用,因为html表是unicode对象格式。

2 个答案:

答案 0 :(得分:0)

使用lxml.html:

的示例
from lxml import html

tree = html.fromstring('<html>Your HTML code</html>')
rows = tree.xpath('//table/tr') #update your table XPath here
records = []
for row in rows:
    cells = [c for c in row.xpath('./td/text()') if c.strip()]
    # do something with cells content

答案 1 :(得分:0)

使用正则表达式:

import re 

s = """<thead><tr> .... </tr></thead>
<tbody>
<tr><td>col1val1</td><td>col2val1</td></tr>
<tr><td>col1val2</td><td>col2val2</td></tr>
<tr><td>col1val3</td><td>col2val3</td></tr>
</tbody> """

lines = s.splitlines()
for line in lines[2:]:
    #print line
    match = re.findall("<td>(.+?)</td>", line)
    for m in match:
        print m