理解爬虫原理
作业来源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2881
1. 简单说明爬虫原理
什么是爬虫?
爬虫:请求网站并提取数据的自动化程序
百科:网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。另外一些不常使用的名字还有蚂蚁、自动索引、模拟程序或者蠕虫。
爬虫原理:
模拟计算机对服务器发起Request请求;
接收服务器的Response内容并解析、提取所需的信息。
2. 理解爬虫开发过程
1).简要说明浏览器工作原理;
通过浏览器向目标站点发送请求,经过服务器的处理之后又通过浏览器做出反应。
2).使用 requests 库抓取网站数据;
requests.get(url) 获取校园新闻首页html代码
|
1
2
3
4
|
import requestsres=requests.get('http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0322/11047.html')res.encoding='utf-8'res.text |
3).了解网页
写一个简单的html文件,包含多个标签,类,id
|
1
2
3
4
5
6
7
|
<html> <body> <h1 id="title">Hello</h1> <a href="#" class="link"> This is link1</a><a href="#link2" class="link" num=2019> This is link2</a> <p id="info">This is info </body></html>' |
4).使用 Beautiful Soup 解析网页;
通过BeautifulSoup(html_sample,'html.parser')把上述html文件解析成DOM Tree
|
1
|
soup=BeautifulSoup(html_hjy,'html.parser') |
select(选择器)定位数据
|
1
2
|
t = news.select('#title')l = news.select('.link') |
找出含有特定标签的html元素
|
1
2
|
t=soup.select('h1')[0].textprint(t) |
找出含有特定类名的html元素
|
1
2
3
|
for i in range(len(soup.select('.link'))): d=soup.select('.link')[i].text print(d) |
找出含有特定id名的html元素
|
1
2
|
info=soup.select('#info')[0].textprint(info) |
3.提取一篇校园新闻的标题、发布时间、发布单位
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import requestsfrom bs4 import BeautifulSoupurl='http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html'#网络资源获取res=requests.get(url)res.encoding='utf-8'# 解析成DOM Treesoup=BeautifulSoup(res.text,'html.parser')# 提取详细信息t = soup.select('.show-title')[0].textfor 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 |
结果如下:


浙公网安备 33010602011771号