我正试图从https://pll.harvard.edu/catalog/free的哈佛大学网站上删除免费课程的名称和链接,使用的是Python和BeautifulSoup
我已经获得了每门课程的名称,但在try 提取指向该课程的链接时遇到了问题.例如,对于CS50的《S游戏开发入门》,以下是指向课程页面的链接的html:
<div class="field field--name-title field--type-string field--label-hidden field__items">
<h3 class="field__item"><a href="/course/cs50s-introduction-game-development" hreflang="en">CS50's Introduction to Game Development</a></h3>
</div>
我正在try 为页面上列出的每一门课程在a属性中获取"/Course/cs50s-Introduction-Game-Development"部分.
这是我目前拥有的获取课程名称的代码:
#gets the soup of the given url
def get_data(url):
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
return soup
#gets the name and skill from each course and prints them
def get_all_content(firstURL):
url = firstURL
for i in range(1, 10):
soup = get_data(url)
print("PRINTING PAGE: " + str(url))
course_names = soup.findAll("h3", attrs={"class": "field__item"})
skills = soup.findAll("div", attrs={"class": "field field--name-title field--type-string field--label-hidden field__items"})
for course, skill in zip(course_names, skills):
print(course.text + "\n" + skill.text)
url = f'http://pll.harvard.edu/catalog/free?page={i}'
print("PRINTING NEWLY GOTTTEN URL: " + str(url))
#sleep(randint(2, 10))
get_all_content(firstURL)
我try 了以下解决方案来获得href,从网上和研究中获得的.我最接近的情况是,在上面的第一个for循环中添加了以下内容:
for div in soup.findAll("div", attrs={"class": "field field--name-title field--type-string field--label-hidden field__items"}):
page_link = div.findAll("h3", attrs={"class":"field__item"})
print("PRINTING LINK: " + str(page_link))
它为第一道菜打印了以下内容:
打印链接:[<h3 class="field__item"><a href="/course/cs50s-introduction-game-development" hreflang="en">CS50's Introduction to Game Development</a></h3>]
我所期待的只是这款part:"/course/cs50s-introduction-game-development"
我try 了许多我在网上找到的解决方案,但我经常收到错误,如FIND_ALL无法在此使用,或者没有一个没有Find属性或类似的错误.我对Python(本周开始)非常陌生,我不确定如何进一步改进这一点,语法非常令人困惑,我已经对其进行了研究,并达到了这个阶段.我已经将它降低到h3,它非常接近我正在寻找的东西,我觉得解决方案是如此简单,但我已经连续两天在它上面工作,但没有成功.我很感激你们的帮助.如何从div中的h3中的a属性中提取href?