作业要求来自于 https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2881
1. 简单说明爬虫原理
利用程序模拟客户向浏览器发送请求,然后获取返回的响应,最后根据需要处理响应,获取需要的数据。
2. 理解爬虫开发过程
1).简要说明浏览器工作原理;
用户通过url向浏览器发送请求,浏览器解析请求,发送给web服务器,web服务器根据发送的请求类型,返回数据给浏览器,浏览器解析数据,再显示给用户。
2).使用 requests 库抓取网站数据;
requests.get(url) 获取校园新闻首页html代码
3).了解网页
写一个简单的html文件,包含多个标签,类,id
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style type="text/css"> 7 h1.exampleh1 { 8 color:blue; 9 } 10 span.examplesp { 11 text-align: center; 12 } 13 div.examplediv { 14 background-color: grey; 15 } 16 </style> 17 </head> 18 <body> 19 <div class="examplediv" id="myDiv"> 20 <span class="examplesp" id="mySpan"> 21 <h1 class="example" id="myH1">h1标签</h1> 22 </span> 23 </div> 24 </body> 25 </html>
4).使用 Beautiful Soup 解析网页;
通过BeautifulSoup(html_sample,'html.parser')把上述html文件解析成DOM Tree
select(选择器)定位数据
找出含有特定标签的html元素
找出含有特定类名的html元素
找出含有特定id名的html元素
3.提取一篇校园新闻的标题、发布时间、发布单位、作者、点击次数、内容等信息
如url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html'
要求发布时间为datetime类型,点击次数为数值型,其它是字符串类型。
代码:
1 import requests 2 from bs4 import BeautifulSoup 3 import re 4 from datetime import datetime 5 # 新闻的标题、发布时间、发布单位、作者、点击次数、内容 6 pattern = r'发布时间:([0-9-s:]+)作者:(.*)审核:(.*)来源:(.*)点击:(.*)' 7 new_url=r'http://news.gzcc.cn/html/2019/meitishijie_0225/10895.html' 8 clicknum_url = r'http://oa.gzcc.cn/api.php?op=count&id=10895&modelid=80' 9 response = requests.get(new_url) 10 click_response = requests.get(clicknum_url) 11 clicknum = click_response.text 12 clicknum = int(clicknum.split("'")[-2]) 13 response.encoding = 'utf-8' 14 resopnse = response.text 15 soup = BeautifulSoup(resopnse, 'html.parser') 16 title = soup.title.text 17 release_msg = soup.select('.show-info')[0].text 18 result = re.match(pattern,release_msg) 19 result = result.groups() 20 date_str = result[0].split() 21 date_str = ' '.join(date_str) 22 author = result[1] 23 shenhe = result[2] 24 source = result[3] 25 date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S') 26 content = soup.select('#content')[0].text.strip() 27 print('发布时间:', end='') 28 print(date) 29 print('作者:' + author) 30 print('审核:' + shenhe) 31 print('来源:' + source) 32 print('点击数:', end='') 33 print(clicknum) 34 print('内容:' + ' ' + content)
运行效果: