目的:

使用requests库以及xpath解析进行实验楼所有课程,存入MySQL数据 库中。

准备工作:

首先安装,requests库,lxml库,以及peewee库。在命令行模式,使用以下命令。

pip install requests
pip install lxml
pip install peewee

  然后,就可以打开编辑器编写代码了。

代码:

 # 引入所需要的库
import time
import requests
from peewee import *
from lxml import etree
# 这个程序要倒着看 # 这个是连接数据库的,名字和密码根据自己情况修改
db = MySQLDatabase('shiyanlou', user='root', passwd='xxxxxx') class Course(Model):
title = CharField()
teacher = CharField()
teacher_courses = IntegerField()
tag = CharField()
study_num = IntegerField()
content = CharField() class Meta:
database = db Course.create_table() def parse_content(url, title, tag, study_num):
print('课程地址:' + url)
res = requests.get(url)
xml = etree.HTML(res.text)
# 获取页面里的简介
try:
content = xml.xpath('//meta[@name="description"]/@content')[0]
except Exception as e:
content = '无'
# 获取老师名字
try:
teacher = xml.xpath(
'//div[@class="sidebox mooc-teacher"]//div[@class="mooc-info"]/div[@class="name"]/strong/text()')[0]
except Exception as e:
teacher = '匿名'
# 获取老师发表课程数目
try:
teacher_courses = xml.xpath(
'//div[@class="sidebox mooc-teacher"]//div[@class="mooc-info"]/div[@class="courses"]/strong/text()')[0]
except Exception as e:
teacher_courses = '未知'
# 存入数据库
try:
course = Course(title=title, teacher=teacher,
teacher_courses=int(teacher_courses), tag=tag, study_num=int(study_num), content=content)
course.save()
except Exception as e:
print('一条数据存取失败') def get_course_link(url):
# 获取每一页的信息,传给下一个函数
response = requests.get(url)
xml = etree.HTML(response.text)
# contains()是包含的意思
courses = xml.xpath(
'//div[contains(@class, "col-md-3") and contains(@class, "col-sm-6") and contains(@class, "course")]')
for course in courses:
try:
url = 'https://www.shiyanlou.com' + course.xpath('.//a/@href')[0]
except Exception as e:
print('一个课程页面未获得')
continue
title = course.xpath('.//div[@class="course-name"]/text()')[0]
study_people = course.xpath(
'.//span[@class="course-per-num pull-left"]/text()')[1].strip()
# study_people = int(study_people)
try:
tag = course.xpath(
'.//span[@class="course-money pull-right"]/text()')[0]
except Exception as e:
tag = "普通"
parse_content(url=url, title=title, tag=tag, study_num=study_people)
# time.sleep(0.5) def main():
# 通过requests库的get获得目标地址的返回信息,类型为Response
response = requests.get('https://www.shiyanlou.com/courses/')
# 将返回信息的文本转化为xml树,可以通过xpath来进行查询
xml = etree.HTML(response.text)
# 由分析网页源代码可以总结,url分页模式,只有最后的数字不一样
course_link = 'https://www.shiyanlou.com/courses/?category=all&course_type=all&fee=all&tag=all&page={}'
# 这里获得最大页数就可以了,xpath()函数里的便是寻找路径了
# //会在全文来进行查找,//ul则是查找全文的ul标签,//ul[@class="pagination"]会仅查找有class属性,
# 且为"pagination"的标签,之后/li是查找当前的ul标签下的li标签(仅取一层),取查询到的列表倒数第二个标签
# 为li[last()-1],/a/text()查询a标签里的文本内容
page = xml.xpath('//ul[@class="pagination"]/li[last()-1]/a/text()')
if len(page) != 1:
print('爬取最大页数时发生错误!!')
return None
# page原是一个列表,这里取出它的元素,并转化为Int型
page = int(page[0])
# 将每一页的url传给get_course_link函数进行处理
for i in range(1, page + 1):
# 填入course_link,获取完整url
url = course_link.format(i)
print('页面地址:' + url)
# 调用另一个函数
get_course_link(url) if __name__ == '__main__':
# 调用main函数
main() # [Finished in 218.5s]

Python爬虫,爬取实验楼全部课程的更多相关文章

  1. python爬虫—爬取英文名以及正则表达式的介绍

    python爬虫—爬取英文名以及正则表达式的介绍 爬取英文名: 一.  爬虫模块详细设计 (1)整体思路 对于本次爬取英文名数据的爬虫实现,我的思路是先将A-Z所有英文名的连接爬取出来,保存在一个cs ...

  2. Python爬虫 - 爬取百度html代码前200行

    Python爬虫 - 爬取百度html代码前200行 - 改进版,  增加了对字符串的.strip()处理 源代码如下: # 改进版, 增加了 .strip()方法的使用 # coding=utf-8 ...

  3. 用Python爬虫爬取广州大学教务系统的成绩(内网访问)

    用Python爬虫爬取广州大学教务系统的成绩(内网访问) 在进行爬取前,首先要了解: 1.什么是CSS选择器? 每一条css样式定义由两部分组成,形式如下: [code] 选择器{样式} [/code ...

  4. 使用Python爬虫爬取网络美女图片

    代码地址如下:http://www.demodashi.com/demo/13500.html 准备工作 安装python3.6 略 安装requests库(用于请求静态页面) pip install ...

  5. Python爬虫|爬取喜马拉雅音频

    "GOOD Python爬虫|爬取喜马拉雅音频 喜马拉雅是知名的专业的音频分享平台,用户规模突破4.8亿,汇集了有声小说,有声读物,儿童睡前故事,相声小品等数亿条音频,成为国内发展最快.规模 ...

  6. python爬虫爬取内容中,-xa0,-u3000的含义

    python爬虫爬取内容中,-xa0,-u3000的含义 - CSDN博客 https://blog.csdn.net/aiwuzhi12/article/details/54866310

  7. Python爬虫爬取全书网小说,程序源码+程序详细分析

    Python爬虫爬取全书网小说教程 第一步:打开谷歌浏览器,搜索全书网,然后再点击你想下载的小说,进入图一页面后点击F12选择Network,如果没有内容按F5刷新一下 点击Network之后出现如下 ...

  8. 一个简单的python爬虫,爬取知乎

    一个简单的python爬虫,爬取知乎 主要实现 爬取一个收藏夹 里 所有问题答案下的 图片 文字信息暂未收录,可自行实现,比图片更简单 具体代码里有详细注释,请自行阅读 项目源码: # -*- cod ...

  9. python爬虫-爬取百度图片

    python爬虫-爬取百度图片(转) #!/usr/bin/python# coding=utf-8# 作者 :Y0010026# 创建时间 :2018/12/16 16:16# 文件 :spider ...

  10. python爬虫---爬取王者荣耀全部皮肤图片

    代码: import requests json_headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win ...

随机推荐

  1. 线程池(3)Executors.newCachedThreadPool

    例子: ExecutorService es = Executors.newCachedThreadPool(); try { for (int i = 0; i < 20; i++) { Ru ...

  2. kali linux 通过跑包的方式破解wifi密码

    1. wlan0开启monitor mode    :    airmon-ng start wlan0 2. 查看附近的无线网络     : airodump-ng wlan0mon 3. 抓取无线 ...

  3. 七,JOBC数据库编程

    七,JOBC数据库编程 七,JOBC数据库编程 一,java数据库编程步骤 1,将数据库驱动包考入lib目录: 2,加载驱动--整个操作数据库程序运行期间只需要加载一次 Class.forName(& ...

  4. 192.168.28.168:3000打开网页无法调试localhost为前缀的接口

    最近我在IIS上发布.net Core API的时候发现 当我用localhost去打开我的web项目时 并且,ajax调用的接口前缀为localhost时候,运行正确 但是当我用192.168.28 ...

  5. ES6 Interator

    Interator "集合"数据的结构主要有 Array .Object. Set and Map ,任何数据结构只要部署 Iterator 接口,就可完成遍历操作 遍历过程: 创 ...

  6. There is much opportunity for anyone willing to dedicate himself to his labors.

    There is much opportunity for anyone willing to dedicate himself to his labors.付出努力的人才有机会出人头地.

  7. linux命令行—《命令行快速入门》

    pwd print working directory 打印工作目录 hostname my computer's network name 电脑在网络中的名称 mkdir make director ...

  8. Setting 之dashboard 点击跳转流程

    设置的主界面的可以通过修改xml中的dashboard_categaries.xml 文件实现,在DashboardSummary.java 文件中的rebuildUI()方法中将xml对应的实体类转 ...

  9. uvm_reg_block——寄存器模型(七)

    这是寄存器模型的顶层 //------------------------------------------------------------------------ // Class: uvm_ ...

  10. Json字符串与js数组互相转换

    1.Json数据格式的字符串转换成js数组: JSON.parse(str); // str 字符串格式   2.js数组转换成Json数据格式字符串: var myJSONText = JSON.s ...