【发布时间】:2020-08-20 07:49:38
【问题描述】:
我正在收集我的faculty 的所有考试日期以跟踪更改等。
我的代码:
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="" ""><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=" " role="row" class="odd"><td class="sorting_1"><a href="pruefungstermin.php?func=exam&pruef_id=618552&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&pIntervall=2020"><img src="/img/ical_icon.png" width="16" height="16" alt="iCal Eintrag"></a></td></tr>
谁能说出它为什么在这个条目之前有效?
提前致谢
【问题讨论】:
-
您能否提供指向整个页面的链接或在您提供的数据中包含上一行?能否请您删除“Neue Chemie”周围的格式错误的样式标签,看看有什么效果?
-
print(len(exams))显示 467,与表格下方的数字匹配。 -
不工作。没有跨度它正在工作。链接已添加。
-
这意味着它正在正确检测
。但是为什么所有的html代码都在一个字段中呢?
标签: python html beautifulsoup web-crawler