Python BeautifulSoup-提取文本和属性值

时间:2018-11-18 05:18:50

标签: python html beautifulsoup

我有一些HTML:

<td class="course-section-type"><span class="text-capitalize">lecture (5)</span></td>
<td class="course-section-meeting">
   <table class="no-borders" width="100%">
      <tbody>
         <tr>
            <td width="23%">MWF</td>
            <td width="55%">11:30 AM - 12:20 PM</td>
            <td width="22%"><span><a href="http://myurl.com" target="_blank">MGH</a> <span class="sr-only">building room</span> 389</span></td>
         </tr>
      </tbody>
   </table>
</td>
<td class="course-section-sln">00000</td>    

我想提取顶级“类”属性的值并将其映射到较低级文本的列表。对于上述HTML,它看起来像:

data = {
    "course-section-type": ["lecture (5)"],
    "course-section-meeting": ["MWF", "11:30 AM - 12:20 PM", "MGH", "building room", "389"],
    "course-section-sln": ["00000"]
}    

我知道我可以使用soup.findAll('td').text提取所有文本,但是我不知道如何遍历html树,也不知道如何提取tag属性的值。我将如何去做?

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

弄清楚了。事实证明,BeautifulSoup提供了一个关键字参数aliases,该关键字参数在某个标签下(使用顺序遍历)查找所有文本并将其放在列表中。

findAll(text=True)

答案 1 :(得分:0)

解决方案是提取此模式中的所有内容,

由于其表位于表中,因此必须修复该模式,否则下次更改时,一切都会再次中断

course-section-type是外部表格的第一<td>文本

course-section-meeting是内部表的所有文本

course-section-sln是外部表格的第三<td>文本