代码参考自课程
项目内容:爬取天善智能学院课程的名称、讲师、价格
项目工具:re,requests
项目代码:
# @Time : 2020/4/1 20:32
# @Author : w
# @File : 爬取天善课程.py
# @Software: PyCharm
import re
import requests
#利用for循环实现相似网页的连续爬取
for i in range(0,100):
urls="https://edu.hellobi.com/course/"+str(i+1)
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
}
response=requests.get(urls,headers=headers)
#正则表达式来匹配 (.*?)括号里是需要的,返回的部分
title_pa='<li class="active">(.*?)</li>'
teacher_pa='class="lec-name">(.*?)<'
price_pa = 'm-price.*?</sub>(.*?)</span>'
#用findall来查找内容,if-else对内容做一个判断
title=re.compile(title_pa, re.S).findall(response.text)
if(len(title)>0):
print(title)
else:
continue
teacher=re.compile(teacher_pa, re.S).findall(response.text)
if(len(teacher)>0):
print(teacher)
else:
print('lost')
price=re.compile(price_pa, re.S).findall(response.text)
if(len(price)>0):
print(price)
else:
print("free")
print("------------------------------")
#代码截至2020.4.1测试无误
学习点:
利用for循环来更换页面
利用字符串相加urls="https://edu.hellobi.com/course/"+str(i+1)
来改变url
带请求头