gpt4 book ai didi

Python BeautifulSoup - 提取文本和属性值

转载 作者:行者123 更新时间:2023-12-01 01:25:42 28 4
gpt4 key购买 nike

我有一些 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 树,也不知道如何提取标签属性的值。我该如何去做呢?

感谢任何帮助。

最佳答案

想通了。结果 BeautifulSoup 提供了一个关键字参数 findAll(text=True) 来查找某个标签下的所有文本(使用中序遍历)并将其放入列表中。

d = {}
for tag in line.findAll('td'):
if tag.get("class") and "course" in tag.get("class")[0]:
d[tag.get("class")[0]] = [text.strip() for text in tag.findAll(text=True)]
>>> d
{"course-section-type": ["lecture (5)"],
"course-section-meeting": ["MWF", "11:30 AM - 12:20 PM", "MGH", "building room",
"389"], "course-section-sln": ["00000"]}

关于Python BeautifulSoup - 提取文本和属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53358125/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com