【问题标题】:Confusion to read html table contents using BeautifulSoup?使用 BeautifulSoup 读取 html 表格内容感到困惑?
【发布时间】:2013-01-04 11:44:09
【问题描述】:

这是HTML的内容:

<table cellspacing="1" cellpadding="0" class="data">
<tr class="colhead">
            <th colspan="3">Expression</th>
        </tr>
        <tr class="colhead">
            <th>Task</th>
            <th>Action</th>
            <th>List</th>
</tr>           
<tr class="rowLight">
    <td width="40%">
            Task1
        </td>
        <td width="20%">
             Assigned to 
        </td>
        <td width="40%">
             Harry
    </td>

</tr>           
<tr class="rowDark">
     <td width="40%">
                    Task2
                </td>
                <td width="20%">
                     Rejected by 
                </td>
                <td width="40%">
                    Lopa 
                </td>
</tr>

<tr class="rowLight">
    <td width="40%">
            Task5
        </td>
        <td width="20%">
             Accepted By 
        </td>
        <td width="40%">
            Mathew
        </td>
</tr>

现在我必须得到如下值:(下表只是一个 Excel 表,一旦达到这些值,我将建立它。)

Task    Action        List
Task1   Assigned to   Harry
Task2   Rejected by   Lopa
Task5   Accepted By   Mathew

我所知道的外行解决方案如下:

   from bs4 import BeautifulSoup
   soup = BeautifulSoup(source_URL)

alltables = soup.findAll( "table", {"border":"2", "width":"100%"} )

t = [x for x in soup.findAll('td')]

[x.renderContents().strip('\n') for x in t]

但是在我上面的HTML 内容中没有这样的结构,那么如何处理呢?请在这里指导我!

【问题讨论】:

  • 谁能帮帮我?

标签: python python-2.7 beautifulsoup


【解决方案1】:

使用.stripped_strings 从表格行中获取“有趣”的文本:

rows = table.find_all('tr', class_=('rowLight', 'rowDark'))
for row in rows:
    print list(row.stripped_strings)

这个输出:

[u'Task1', u'Assigned to', u'Harry']
[u'Task2', u'Rejected by', u'Lopa']
[u'Task5', u'Accepted By', u'Mathew']

或者,将所有内容拉入一个列表列表(根据请求,最后一行不包括在内):

data = [list(r.stripped_strings) for r in rows[:-1]]

变成:

data = [[u'Task1', u'Assigned to', u'Harry'], [u'Task2', u'Rejected by', u'Lopa']]

.find_all() 的结果,ResultSet,就像 Python 列表一样,您可以随意对其进行切片以忽略某些行。

【讨论】:

  • Woowwwwwww............你就像我的Pyhton-bs-4上帝!好吧,我忘了提到一件事,那就是 - (a) I am not interested to roll over to last row of the table,only last row - 2`。那么该怎么做呢? (b) 如果我想获取每个列表的值,应该采用哪种方式?
  • 我上面说的有可能吗? @Martijin
  • rows 列表和其他列表一样;你可以切片:rows[:-1]。要将这一切变成一个列表列表,请执行data = [list(r.stripped_strings) for r in rows[:-1]]
  • 你能编辑你的code吗,我是这个平台的新手。所以需要时间来了解这一切是什么以及如何?
  • 你完美地抓住了我,但我想你错过了一件事情!那就是当我们遍历rows 时,我将如何限制迭代次数,比如说如果我不需要总是去最后两行!
猜你喜欢
  • 1970-01-01
  • 2022-10-17
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 2012-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多