【发布时间】:2021-11-02 00:18:49
【问题描述】:
我正在制定下学期的时间表。我想提高效率,所以我试图抓取我大学的页面以提取所有课程及其先决条件。我将 Python 与 requests 和 BeautifulSoup 一起使用。
我在提取必须的先决条件和推荐的先决条件列表时遇到了一些麻烦。示例:
<div id="content">
<!-- ... -->
<p>
<img src="gifs/triangle.jpg" width="5" height="10" alt="" border="0" /> Must: The courses
<a href="DOMAIN/courses/12345.htm" target="_blank">Linear Algebra 101</a>,
<a href="DOMAIN/courses/12346.htm" target="_blank">Calculus 101</a> (12346)<span class="heara"><a href="#remarks">2</a></span> and one of
<a href="DOMAIN/courses/12347.htm" target="_blank">Introduction to Statistics and Probability of Science</a>, <a href="DOMAIN/courses/11231.htm" target="_blank">Probability and Introduction to Computer Science Statistics</a>,
<a href="DOMAIN/courses/12348.htm" target="_blank">Probability theory</a>. Recommended: <a href="DOMAIN/courses/12349.htm" target="_blank">Calculus 102</a> (12349).
<span class="heara"><a href="#remarks">3 </a></span>
</p>
<!-- ... -->
</div>
在这种情况下,内容是:
必修课程:线性代数 101、微积分 101 (12346)2 和统计学概论和概率科学、概率和计算机科学统计学概论、概率论之一。推荐:微积分 102 (12349)。 3
一些注意事项:
- 在这种情况下
Linear Algebra 101和Calculus 101是必须的。也是Introduction to Statistics and Probability of Science, Probability and Introduction to Computer Science Statistics, Probability theory之一。 - 推荐:
Calculus 102。 - 请注意,有些课程带有编号,有些则没有(例如
Calculus 101)。 - 请注意,有一个
#remarks(在我们的例子中是粗体数字 2)。
我正在尝试创建一个字典,例如:
{
"must_courses": [
"12345",
"12346"
],
"must_one_of": [
[
"12347",
"11231",
"12348"
]
],
"recommended": [
"12349"
]
}
但由于某种原因,它真的很难解析,因为:
- 首先,“内容”
div中有几个<p>,由于<p>没有class/id,所以很难找到合适的<p>。<p>号码不固定。通常是第二个或第三个<p> - 某些课程名称的名称中没有课程编号,因此应从
<a href=$url中提取课程编号。 - 我需要检查它的格式是否正确 - 它可以以
Must开头,也可以以Recommended开头。它也可以有“and one of”课程。
我尝试了什么:
soup = bs(r.content, 'html.parser')
content_div = soup.find('div', attrs={'id':'content'})
p_sections = content_div.find_all('p')
for index, p_section in enumerate(p_sections):
if index == 3:
# Sometimes its index 2 and sometimes its index 3
# Tried to use: p_section.text
即使知道<p>是正确的哪个索引,我仍然不知道如何解析该行。
几个例子: 示例 1:
<div id="content">
<!-- ... -->
<p>
<img src="gifs/triangle.jpg" width="5" height="10" alt="" border="0" /> Must: The course <a href="DOMAIN/courses/12346.htm" target="_blank">Calculus 101</a> (12346).
<span class="heara"><a href="#remarks">2</a></span>
</p>
<!-- ... -->
</div>
内容:
必须:微积分 101 (12346) 课程。 2
示例 2:
<div id="content">
<!-- ... -->
<p><img src="gifs/triangle.jpg" width="5" height="10" alt="" border="0" />
Recommended: The course <a href="DOMAIN/courses/04101.htm" target="_blank">Combinatorics</a>.</p>
<!-- ... -->
</div>
内容:
推荐:课程组合。
但我只需要一个关于如何“正确”解析它的示例,我认为我可以使用正则表达式(我认为这是这样做的方法?)来解析不同的行。添加示例以便更容易理解我面临的任务。
【问题讨论】:
标签: python html beautifulsoup python-requests