首页 > 解决方案 > Beautiful Soup 没有检测到 td-tag 的结尾

问题描述

我正在收集我的教师的所有考试日期,以跟踪变化等。

我的代码:

from bs4 import BeautifulSoup
import requests
import csv


data = requests.get('https://www.wiwi.kit.edu/pruefungstermine.php')

soup = BeautifulSoup(data.text, 'lxml')


table = soup.find('tbody').find_all('tr') #finds table with relevant information and returns a list with all entries (is working)

first_row = ('Prüfung', 'Prüfer', 'Datum', 'Zeit/Ort') #header (in German but doesn't matter)

exams = []

for row in table: #looping through every tr
    content = row.find_all('td')
    exam_name = content[0].find('a').text.strip()
    lecturer = content[1].text.strip()
    date = content[2].text.strip()
    time_location = content[3].text.replace('\n', ', ').strip()

    exam = (exam_name, lecturer, date, time_location)
    exams.append(exam)


with open('exams.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(first_row)
    for row in exams:
        writer.writerow(row)

(可能只能循环一次,但这不应该是这里的问题)

它在一定程度上可以正常工作,但是它没有检测到关闭并且最后一个表条目如下所示:

Organisationsmanagement,Lindstädt,13.02.2020,"14.30 - 17.30: Audimax, Neue Chemie</span></td><td class=""dialog""><a href=""/m/ics.php?pruef_id=618550&pIntervall=2020""><img src=""/img/ical_icon.png"" width=""16"" height=""16"" alt=""iCal Eintrag"" /></a></td></tr><tr id=""618551"" title=""&nbsp;""><td><a href=""pruefungstermin.php?func=exam&pruef_id=618551&pIntervall=2020"">Problemlösung, Kommunikation und Leadership (PKL)</a></td><td>Lindstädt</td><td>13.02.2020</td><td>14.30 - 17.30: Audimax, <style=""color:#ff0000;"">Neue Chemie</span></td><td cl ........

这显然是最后一个表条目,因为 Beautiful Soup 不知何故没有检测到,下面的 html 代码放在这里。

本条目的html代码:

<tr id="618552" title="&nbsp;" role="row" class="odd"><td class="sorting_1"><a href="pruefungstermin.php?func=exam&amp;pruef_id=618552&amp;pIntervall=2020">Unternehmensführung und Strategisches Management </a></td><td>Lindstädt</td><td>13.02.2020</td><td>14.30 - 17.30: Audimax, <style="color:#ff0000;">Neue Chemie</style="color:#ff0000;"></td><td class="dialog"><a href="/m/ics.php?pruef_id=618552&amp;pIntervall=2020"><img src="/img/ical_icon.png" width="16" height="16" alt="iCal Eintrag"></a></td></tr>

谁能说出为什么它在此条目之前有效?

提前致谢

标签: pythonhtmlbeautifulsoupweb-crawler

解决方案


我预计这是由于周围的格式错误的样式标签Neue Chemie

<style="color:#ff0000;">Neue Chemie</style="color:#ff0000;">

这不是有效的 html。删除样式标签可能会得到你想要的结果。如果可行,您可以尝试保留样式标签,但使其成为格式正确的标签,而结束标签中没有任何其他信息,这些信息应该总是只读</style>

看了源码,确实是畸形的HTML: 在此处输入图像描述

在这里,您有一个结束但没有开始的跨度。相反,你有一个开口。

根据文件的其余部分,您想要的是一个具有样式属性的开放跨度,例如: <span style="something;">text</span>

其中有很多需要纠正的。您可以通过搜索/替换来做到这一点:

搜索:<style="color:#ff0000

代替:<span style="color:#ff0000


推荐阅读