作业的要求来自于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2851
1. 简单说明爬虫原理
通过程序模拟浏览器请求站点的行为,把站点返回的HTML代码/JSON数据/二进制数据(图片、视频) 爬到本地,进而提取自己需要的数据,存放起来使用。
2. 理解爬虫开发过程
1).简要说明浏览器工作原理;
用户从键盘或触屏输入URL并回车确认
↓
URL解析/DNS解析查找域名IP地址
↓
网络连接发起HTTP请求
↓
HTTP报文传输过程
↓
服务器接收数据
↓
服务器响应请求/MVC
↓
服务器返回数据
↓
客户端接收数据
↓
浏览器加载/渲染页面
↓
打印绘制输出
2).使用 requests 库抓取网站数据;
requests.get(url) 获取校园新闻首页html代码
url='http://news.gzcc.cn/html/tongzhigonggao/' res=requests.get(url)
3).了解网页
写一个简单的html文件,包含多个标签,类,id
<html> <body> <h1 id="title">Hello</h1> <a href="#" class="link">link1</a> <a href="# link2" class="link" qao=123>link2</a> </body> </html>
4).使用 Beautiful Soup 解析网页;
通过BeautifulSoup(html_sample,'html.parser')把上述html文件解析成DOM Tree
select(选择器)定位数据
找出含有特定标签的html元素
找出含有特定类名的html元素
找出含有特定id名的html元素
# -*- coding: utf-8 -*- """ Created on Mon Mar 25 08:48:25 2019 @author: Administrator """ import requests 'print(requests)' import bs4 from bs4 import BeautifulSoup 'print(bs4)' url="https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2" ''' url='http://news.gzcc.cn/html/tongzhigonggao/' ''' res=requests.get(url) res.encoding='utf-8' ''' print(res) print(res.status_code) print(res.encoding) print(res.text) ''' soup=BeautifulSoup(res.text,'html.parser') soup.select('li') ''' for news in soup.select('li'): if len(news.select('.news-list-title'))>0: t=news.select('.news-list-title')[0].text a=news.select('a')[0]['href'] d=news.select('.news-list-info')[0].text print(t,a,d) ''' for news in soup.select('li'): if len(news.select('.am-list-item-hd'))>0: t=news.select('.am-list-item-hd')[0].text a=news.select('a')[0]['href'] print(t,a)
3.提取一篇校园新闻的标题、发布时间、发布单位
url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html'
# -*- coding: utf-8 -*- """ Created on Mon Mar 25 08:48:25 2019 @author: Administrator """ import requests import bs4 from bs4 import BeautifulSoup url="http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html" res=requests.get(url) res.encoding='utf-8' soup=BeautifulSoup(res.text,'html.parser') soup.select('div') for news in soup.select('div'): if len(news.select('.show-title'))>0: t=news.select('.show-title')[0].text b=news.select('.show-info')[0].text print(t,b) break