猿问

美丽的汤解析多个标签

我正在为我的学校评分系统处理数据,并试图弄清楚如何按类别提取数据。


这是原始 HTML:https ://pastebin.com/icbaemd7


现在,我编写了一个 Python 脚本:


html = driver.page_source

soup = BeautifulSoup(html, 'html.parser')


chemData = ((soup.find_all('td')))

content = []

print chemData

print ""

for i in chemData:

    content.append(i.getText().split('</td')[0])

for k in content:

    print (k)

返回此结果:


Safety Contract Signed

1/1

8/13/2019


Student Profile Sheet Turned In

1/1

8/13/2019


Polyatomic Ion Quiz

10/10

8/19/2019


HW Quiz Ch. 3 Target 6

3/3

8/27/2019


HW Quiz (Ch. 3 Targets 1-6)

12/16

8/28/2019


Chapters 1 & 2 Formative Quiz

15/17

8/21/2019


Chapter 3 Formative Quiz

23.5/25

9/5/2019


Lab Report: Antifreeze Lab

10/10

8/21/2019


Types of Reactions Lab Report

11/12

8/23/2019


Hydrate Lab Report

10/10

8/29/2019


Lab Assessment - Types of Reactions Lab

10/15

8/26/2019


Lab Assessment: Hydrate Lab

10/10

9/3/2019

但是,我想将这些分类到 HTML 中存在的类别中。h3如果我使用而不是运行相同的脚本td,我会得到它们:


Homework

Formative Quizzes

Lab Reports

Lab Assessments

所以我的问题是:如何让它自动将实际作业分类到相应的类别中?


任何帮助将不胜感激。谢谢!


潇潇雨雨
浏览 88回答 2
2回答

慕尼黑8549860

尝试以下类似的方法,您可以在其中测试 h3 并制作字典键,否则从当前 dict[key] 下的行中添加值from bs4 import BeautifulSoup as bshtml = '''yourHTML'''soup = bs(html, 'lxml')results = {}for i in soup.select('h3, tr'):&nbsp; &nbsp; if i.name == 'h3':&nbsp; &nbsp; &nbsp; &nbsp; header = i.text&nbsp; &nbsp; &nbsp; &nbsp; results[header] = []&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; results[header].append(' '.join([n.text for n in i.select('td')]))print(results)

BIG阳

您的 html 无法正确呈现。然而,作为快速解决方案,查找包含 h3 标记和每个类别的表的父容器,并首先抓取父容器。例如,让我们假设 h3 标签和表格在一个 div 下。然后先刮掉div 标签,即 d = soup.findall('div')。然后通过 d 进一步循环以提取 h3 标签,然后是 tr/td。前任。d[0].findall('h3') d[0].findall('td') 等等..
随时随地看视频慕课网APP

相关分类

Python
我要回答