@

  这几天爬取了course动态网页的课程信息,有关数据分析机器学习,还有概率论和数理统计课程,这里数据过多,只对数据分析的模块进行了详细爬取。为之后的数据分析以及机器学习情感处理进行数据获取,下面直接上代码和截图:

1.大模块页面

页面如下:



爬取代码:

# encoding: utf-8
from selenium import webdriver
import csv class GetModel():
'''
类功能介绍:获取每页每个大模块的类型,标题,url
类成员变量:browser对象,每页的url
类成员函数:初始化函数__init__,获取每个大模块信息的函数getEveryModel,写入csv的函数saveToCsv
'''
def __init__(self,url):
self.__browser = webdriver.Chrome()
self.__page_url = url def saveToCsv(self,this_list):
with open("model.csv", "a", newline='', encoding='utf-8') as f:
writer = csv.writer(f, delimiter=',')
writer.writerow(this_list) def getEveryModel(self):
# 隐式等待
self.__browser.implicitly_wait(30)
self.__browser.get(self.__page_url)
model_type = self.__browser.find_elements_by_css_selector(".product-type-row.horizontal-box")
model_title = self.__browser.find_elements_by_css_selector(".color-primary-text.card-title.headline-1-text")
model_url = self.__browser.find_elements_by_css_selector(".rc-DesktopSearchCard.anchor-wrapper.browse-result-card") for i in range(len(model_type)):
every_model = []
every_model.append(model_type[i].text)
every_model.append(model_title[i].text)
every_model.append(model_url[i].get_attribute('href'))
self.saveToCsv(every_model) def closeUrl(self):
self.__browser.close()

结果如下:



2.每个大模块中小模块的简单信息

页面如下:



查看全部的信息要先模拟点击查看所有页面:



代码如下:

# encoding: utf-8
from selenium import webdriver
import csv
import time class GetCourse():
'''
类功能介绍:获取每个大模块的小课程的信息
类成员变量:browser对象,每个大模块的url,大模块类别,大模块标题
类成员函数:初始化函数__init__,获取每个小课程信息的函数getEveryCourse,写入csv的函数saveToCsv
'''
def __init__(self,url,model_type,model_title):
self.__browser = webdriver.Chrome()
self.__page_url = url
self.__model_type = model_type
self.__model_title = model_title def saveToCsv(self,this_list):
with open("course2.csv", "a", newline='', encoding='utf-8') as f:
writer = csv.writer(f, delimiter=',')
writer.writerow(this_list) def getEveryCourse(self):
self.__browser.get(self.__page_url)
# 隐式等待
self.__browser.implicitly_wait(15)
try:
button = self.__browser.find_element_by_css_selector(".Button_1w8tm98-o_O-default_9vdknu-o_O-md_1jvotax.m-t-1.d-block.m-x-auto")
button.click()
except:
print("没有多余项")
finally:
self.__browser.implicitly_wait(20)
course_title = self.__browser.find_elements_by_css_selector(".H2_1pmnvep-o_O-weightBold_uvlhiv-o_O-bold_1byw3y2.m-b-2")
# course_url = self.__browser.find_elements_by_css_selector(".Col_i9j08c-o_O-xsCol12_1m1ceo5-o_O-mdCol10_1eb21lj-o_O-lgCol10_ra5osh.p-b-3.border-bottom a")
course_score = self.__browser.find_elements_by_css_selector(".H4_1k76nzj-o_O-weightBold_uvlhiv-o_O-bold_1byw3y2.m-l-1s")
commet_num = self.__browser.find_elements_by_css_selector(".P_gjs17i-o_O-weightNormal_s9jwp5-o_O-fontBody_56f0wi.m-r-1s")
comment_number = self.__browser.find_elements_by_css_selector(".reviewsCount") for i in range(len(course_title)):
every_course = []
every_course.append(course_title[i].text)
every_course.append(course_score[i].text[0:4])
every_course.append(commet_num[i].text)
every_course.append(comment_number[i].text)
every_course.append(self.__model_type)
every_course.append(self.__model_title)
self.saveToCsv(every_course) def closeUrl(self):
self.__browser.close()

结果如下:

3.每个小课程的详细信息

页面如下:



代码如下:

# encoding: utf-8
from selenium import webdriver
import csv class GetDetail():
'''
类功能介绍:获取每个课程的详细信息
类成员变量:browser对象,每个课程的之前已爬取的信息
类成员函数:初始化函数__init__,获取每个课程详细信息的函数getEveryDetail,写入csv的函数saveToCsv
'''
def __init__(self,title,url,score,mark_people_num,comment_people_num,model_type,model_title):
self.__browser = webdriver.Chrome()
self.__page_title = title
self.__page_url = url
self.__score = score
self.__mark_people_num = mark_people_num
self.__comment_people_num = comment_people_num
self.__model_type = model_type
self.__model_title = model_title def saveToCsv(self,this_list):
with open("course_detail.csv", "a", newline='', encoding='utf-8') as f:
writer = csv.writer(f, delimiter=',')
writer.writerow(this_list) def getEveryDetail(self):
self.__browser.get(self.__page_url)
# 隐式等待
self.__browser.implicitly_wait(20)
course_registered_num = self.__browser.find_element_by_css_selector(".enrolledLargeFont_16g5ucx span strong span").text
course_provide = self.__browser.find_element_by_css_selector(".partnerBanner_np2ice-o_O-Box_120drhm-o_O-displayflex_poyjc div img").get_attribute("title")
course_information_view_num = self.__browser.find_element_by_css_selector(".viewsWithTextOnly_1fs65xr span span").text
course_information = self.__browser.find_element_by_css_selector(".content-inner").text what_we_learned = self.__browser.find_elements_by_css_selector(".Col_i9j08c-o_O-xsCol12_1m1ceo5-o_O-mdCol6_1rbv01c.m-b-1")
what_we_learned_result = ''
for i in range(len(what_we_learned)):
what_we_learned_result += what_we_learned[i].text
acquired_skills = self.__browser.find_elements_by_css_selector(".Pill_56iw91.m-r-1s.m-b-1s")
acquired_skills_result = ''
for i in range(len(acquired_skills)):
acquired_skills_result += acquired_skills[i].text
acquired_skills_result += ' ' course_evaluation = self.__browser.find_elements_by_css_selector(".quote.caption-text")
course_evaluation_result = ''
for i in range(len(course_evaluation)):
course_evaluation_result += course_evaluation[i].text
course_evaluation_result += ' ' all_one = self.__browser.find_elements_by_css_selector(".H4_1k76nzj-o_O-weightBold_uvlhiv-o_O-bold_1byw3y2.m-b-0")
all_two = self.__browser.find_elements_by_css_selector(".font-sm.text-secondary")
finish_time = all_one[3].text
advice_time = all_two[2].text
course_language = all_one[4].text
subtitle_language = all_two[3].text course_lecturer = self.__browser.find_elements_by_css_selector(".link-no-style")
course_lecturer_result = ''
for i in range(len(course_lecturer)):
course_evaluation += course_lecturer[i].text
course_lecturer_result += ' ' every_course_detail = []
every_course_detail.append(self.__page_title)
every_course_detail.append(self.__page_url)
every_course_detail.append(self.__score)
every_course_detail.append(self.__mark_people_num)
every_course_detail.append(self.__comment_people_num)
every_course_detail.append(self.__model_type)
every_course_detail.append(self.__model_title)
every_course_detail.append(course_registered_num)
every_course_detail.append(course_provide)
every_course_detail.append(course_information_view_num)
every_course_detail.append(course_information)
every_course_detail.append(what_we_learned_result)
every_course_detail.append(acquired_skills_result)
every_course_detail.append(course_evaluation_result)
every_course_detail.append(finish_time)
every_course_detail.append(advice_time)
every_course_detail.append(course_language)
every_course_detail.append(subtitle_language)
self.saveToCsv(every_course_detail) def closeUrl(self):
self.__browser.close()

结果如下:

4.爬取所有评论

  我把所有的小课程爬取下来,并进行了排名,取前六个如下:



  然后对这六个课程进行了所有评论的爬取。代码如下:

# encoding: utf-8
from selenium import webdriver
import csv
import pandas as pd
import re
import os.path
def saveToCsv(url_title,this_list):
with open("{0}_review.csv".format(url_title), "a", newline='', encoding='utf-8') as f:
writer = csv.writer(f, delimiter=',')
writer.writerow(this_list) def get_review(url_title,i):
'''
:param url_title : 课程标题
'''
try:
url = 'https://www.coursera.org/learn/' + url_title + '/reviews'+ '?page=' + str(i)
browser = webdriver.Chrome()
browser.get(url)
# 隐式等待
browser.implicitly_wait(20)
every_view = browser.find_elements_by_css_selector(".Row_nvwp6p.review.review-page-review.m-b-2")
n = 1
for i in every_view:
s = i.find_elements_by_css_selector(".StarRating_1qk9an0-o_O-nonEditable_1ko0lno label")
# 评星
evaluation_star = 0
for j in s:
if j.text == 'Filled Star':
evaluation_star = evaluation_star + 1
elif j.text == 'Half Faded Star':
evaluation_star = evaluation_star + 0.5
# 作者和时间
author = i.find_element_by_css_selector(".reviewerName.p-x-1s.m-b-0.text-secondary.font-xs").text[4:]
time = i.find_element_by_css_selector(".dateOfReview.p-x-1s.m-b-0.text-secondary.font-xs").text
# 评论
reviewTextAll = i.find_elements_by_css_selector(".reviewText div div p")
ss = []
for j in reviewTextAll:
ss.append(j.text)
reviewText = '@@'.join(ss)
# 点赞数
zan = i.find_element_by_css_selector(".Col_i9j08c-o_O-mdCol4_cuxg7k.e2e-helpful-button-col").text
if zan == '这些很有用:':
like_num = 0
else:
number = re.findall(r"\d+\.?\d*",zan)
like_num = int(number[0])
list_data = []
list_data.append(evaluation_star);list_data.append(author);list_data.append(time);list_data.append(reviewText);list_data.append(like_num)
saveToCsv(url_title, list_data)
n = n + 1
browser.close()
except:
print("出错,继续获取")
get_review(url_title, i) def get_result(url_title,page_num):
# 控制页数
for i in range(1,page_num+1):
try:
get_review(url_title,i) # 爬取第i页的内容
print("*********课程{course}的第{num}页爬取完毕".format(course=url_title, num=i))
except Exception as ex:
print("*********课程{course}的第{num}页爬取出错-{ex}".format(course = url_title,num = i,ex=ex)) def chucuo(k,v):
file_name = "{0}_review.csv".format(k)
# 文件标题
csv_head = ['evaluation_star', 'author', 'time', 'reviewText', 'like_num']
# 写入文件标题
with open(file_name, "a", newline='', encoding='utf-8') as f:
file_empty = os.stat(file_name).st_size == 0
writer = csv.writer(f, delimiter=',')
if file_empty: # 防止因程序重复运行而写入重复的标题
writer.writerow(csv_head)
get_result(k, v) def main():
url_title = {'data-scientists-tools':165,'what-is-datascience':136,'r-programming':124,'python-data-analysis':119,'open-source-tools-for-data-science':60,'python-for-applied-data-science-ai':54}
for k,v in url_title.items():
chucuo(k, v) if __name__=='__main__':
main()

结果如下:



对比原网页如下:





注:多段评论用@@隔开,如下:



python爬取course课程的信息的更多相关文章

  1. 用Python爬取智联招聘信息做职业规划

    上学期在实验室发表时写了一个爬取智联招牌信息的爬虫. 操作流程大致分为:信息爬取——数据结构化——存入数据库——所需技能等分词统计——数据可视化 1.数据爬取 job = "通信工程师&qu ...

  2. python爬取 “得到” App 电子书信息

    前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: 静觅 崔庆才 PS:如有需要Python学习资料的小伙伴可以加点击下 ...

  3. Python爬取房天下二手房信息

    一.相关知识 BeautifulSoup4使用 python将信息写入csv import csv with open("11.csv","w") as csv ...

  4. python爬取北京政府信件信息01

    python爬取,找到目标地址,开始研究网页代码格式,于是就开始根据之前学的知识进行爬取,出师不利啊,一开始爬取就出现了个问题,这是之前是没有遇到过的,明明地址没问题,就是显示网页不存在,于是就在百度 ...

  5. Python 爬取赶集网租房信息

    代码已久,有可能需要调整 #coding:utf-8 from bs4 import BeautifulSoup #有这个bs4不用正则也可以定位要爬取的内容了 from urlparse impor ...

  6. 利用python爬取贝壳网租房信息

    最近准备换房子,在网站上寻找各种房源信息,看得眼花缭乱,于是想着能否将基本信息汇总起来便于查找,便用python将基本信息爬下来放到excel,这样一来就容易搜索了. 1. 利用lxml中的xpath ...

  7. python爬取实习僧招聘信息字体反爬

    参考博客:http://www.cnblogs.com/eastonliu/p/9925652.html 实习僧招聘的网站采用了字体反爬,在页面上显示正常,查看源码关键信息乱码,如下图所示: 查看网页 ...

  8. Python爬取简书主页信息

    主要学习如何通过抓包工具分析简书的Ajax加载,有时间再写一个Multithread proxy spider提升效率. 1. 关键点: 使用单线程爬取,未登录,爬取简书主页Ajax加载的内容.主要有 ...

  9. Python爬取B站视频信息

    该文内容已失效,现已实现scrapy+scrapy-splash来爬取该网站视频及用户信息,由于B站的反爬封IP,以及网上的免费代理IP绝大部分失效,无法实现一个可靠的IP代理池,免费代理网站又是各种 ...

随机推荐

  1. web项目中设置首页

    1.在web.xml中设置以下代码: <welcome-file-list> <welcome-file>login.jsp</welcome-file> < ...

  2. ASP.NET + MVC5 入门完整教程二

    原文链接:https://blog.csdn.net/qq_21419015/article/details/80318046 从前端UI开始 MVC分离的比较好,开发顺序没有特别要求,先开发哪一部分 ...

  3. 【js】子菜单吸顶(滚动到一定距离 容器置顶)附 无间断置顶 避免闪动

    思考逻辑:当向上滚动的高度>= 观察容器距离顶部高度 即可触发吸顶 以下代码在vue工程,作参考 handleScroll () { const scrollTop = window.pageY ...

  4. C#中数据类型char*,const char*和string的三者转换

    C#中数据类型char*,const char*和string的三者转换: . const char* 和string 转换 () const char*转换为 string,直接赋值即可. EX: ...

  5. zookeeper linux分布式部署

    安装包下载地址:http://mirror.bit.edu.cn/apache/zookeeper,记住要下载那个bin的不要下tar.gz包不然即使你安装了也会报错误: 找不到或无法加载主类org. ...

  6. Vue-移动端开发全家桶

    内容:node.js,vue-cli,vuex,axios,postcss-pxtorem,lib-flexible,vant ,babel-plugin-import 1.安装脚手架工具: npm ...

  7. Qt那点事儿(一)

    原文http://www.cnblogs.com/andreitang/archive/2011/08/03/2125815.html 第一回 Signal和Slot是同步的还是异步的? 我们知道Qt ...

  8. 使用SqlDataReader的查询操作

    原创weixin_42430576 发布于2019-01-31 18:49:41 阅读数 762  收藏 展开 using System; using System.Collections.Gener ...

  9. Bugku-CTF之求getshell

    Day31 求getshell   http://123.206.87.240:8002/web9/      

  10. 路飞-自定义User表和Media配置

    user模块User表 创建user模块 """ 前提:在 luffy 虚拟环境下 1.终端从项目根目录进入apps目录 >: cd luffyapi & ...