【分享】使用爬虫获取CSDN学院里所有免费的视频课

Dagny ·
更新时间:2024-09-20
· 624 次阅读

【分享】使用爬虫获取CSDN学院里所有免费的视频课

大家好,我是Samaritan。
自学了一周爬虫,出于需求想在学院视频课里找找有没有适合学习的,发现找不到只看免费课的过滤器(也可能是我高度近视),于是就当练手,写了这个爬虫,希望能帮到和我一样需求的朋友。

好了,Talk is cheap,show you the code!

#爬取csdn学院中所有标注免费的视频课,并将标题和链接保存到txt里(默认路径为桌面) import requests from bs4 import BeautifulSoup as bts #使用两个爬虫最常用的库 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'} url = 'https://edu.csdn.net/course/index/p1?is_member=1&is_free=2' #创建请求头和需要爬取的url key ='免费' #设置爬取判定的关键字 res = requests.get(url,headers=headers) print(res.status_code) #检查响应状态 html = bts(res.text,'html.parser') page = html.find(class_="page-nav").find_all('a') count=[] #获得学院里要爬取课程的总页数,并创建个列表 for p in page: try: count.append(p.text) except: pass count.sort() pagemax = int(count[-1]) #将列表数字排序,得到最大页数 file = open(r'C:\Users\Raytine\Desktop\csdnfree.txt','w',encoding='utf-8') #创建文件(可以修改路径) for collect in range(pagemax): urlx = 'https://edu.csdn.net/course/index/p{}?is_member=1&is_free=2'.format(collect+1) #遍历得到了所有课程页面的url resx = requests.get(urlx, headers=headers) htmlx = bts(resx.text,'html.parser') soup = htmlx.find(class_="course_html course_card_list clearfix").find_all(class_="course_item") for i in soup: try: kind = i.find('i',class_="free").text.strip() if kind == key: #判断课程是否免费 title = i.find(class_="title ellipsis-2").text.strip() link =i.find('a') file.writelines('\n'+title+'\n'+link['href']+'\n') #将免费课程的标题和链接写入刚刚创建的文件 except: pass file.close() print('爬取成功!') #关闭文件,提示爬取成功,可以去查收了~

代码就到这里了,如果对你有用的话我会很开心~

欢迎和我差不多情况的朋友一起讨论python和爬虫,如有大佬不吝赐教,无比感谢。

Value=Valueless 原创文章 1获赞 0访问量 256 关注 私信 展开阅读全文
作者:Value=Valueless



爬虫 csdn

需要 登录 后方可回复, 如果你还没有账号请 注册新账号