理解爬虫原理
1. 简单说明爬虫原理
如果我们把互联网比作一张大的蜘蛛网,数据便是存放于蜘蛛网的各个节点,而爬虫就是一只小蜘蛛,沿着网络抓取自己的猎物(数据)爬虫指的是:向网站发起请求,获取资源后分析并提取有用数据的程序;从技术层面来说就是 通过程序模拟浏览器请求站点的行为,把站点返回的HTML代码/JSON数据/二进制数据(图片、视频) 爬到本地,进而提取自己需要的数据,存放起来使用;
2. 理解爬虫开发过程
1).简要说明浏览器工作原理:
浏览器工作原理的实质就是实现http协议的通讯,具体过程如下:(HTTP通信的流程,大体分为三个阶段)
- 连接,服务器通过一个ServerSocket类对象对某端口进行监听,监听都之后进行连接,打开一个socket虚拟文件。
- 请求,创建与监理socket连接相关的流对象后,浏览器获取请求,为get请求,则从请求信息中获取所访问的html文件名,向服务器发送请求。
- 响应,服务器收到请求后,搜索相关的目录文件,若不存在,返回错误的信息。若存在,则读取html文件,进行加http头等处理响应给浏览器,浏览器解析html文件,若其中还包含图片,视频等资源,则浏览器再次访问web服务器,获取图片视频等,并对其进行组装显示给用户。
2).使用 requests 库抓取网站数据;
requests.get(url) 获取校园新闻首页html代码
3).了解网页
写一个简单的html文件,包含多个标签,类,id
<!DOCTYPE html>
<html>
<head>
<meta charset
=
"utf-8"
/
>
<title><
/
title>
<link href
=
"css/ad.css"
rel
=
"stylesheet"
type
=
"text/css"
/
>
<script src
=
"js/jquery.js"
><
/
script>
<
/
head>
<body>
<div
id
=
"Textbody"
>
<h1>音乐<
/
h1>
<div
class
=
"AD"
>
<form
id
=
"form1"
>
信息:<
input
class
=
"input1"
value
=
"z kkp"
/
>
<br>
<
/
form>
回复:<
input
class
=
"input1"
value
=
"gkp"
/
>
<
/
div>
<br>
<h1> 现代 > 古代<
/
h1>
<div
class
=
"PC"
>
<span>
span
#child
<
/
span>
<
/
div>
<br>
<span>
不是现代音乐
<
/
span>
<br>
<h1> 现
+
古<
/
h1>
<div
class
=
"PN"
>
<span>前面<
/
span>
<
/
div>
<div>后面(是紧接着的一个元素)<
/
div>
<br>
<br>
<h1>古<
/
h1>
<div
class
=
"PS"
>
<div>现代
1
<
/
div>
<p>古代
2
<
/
p>
<button>音乐
3
<
/
button>
<
/
div>
<
/
div>
<
/
body>
<
/
html>
4).使用 Beautiful Soup 解析网页;
通过BeautifulSoup(html_sample,'html.parser')把上述html文件解析成DOM Tree
select(选择器)定位数据
找出含有特定标签的html元素
找出含有特定类名的html元素
找出含有特定id名的html元素
1
|
simple = open (r 'C:\Backup\桌面\index.html' , 'r' ,encoding = 'utf-8' ) |
simpleR = simple.read()
soup=BeautifulSoup(simpleR,'html.parser')
1
2
3
4
|
h = soup.select( 'h1' ) id = soup.select( '#from1' ) cls = soup.select( '.AD' ) print (h, id , cls ) |
3.提取一篇校园新闻的标题、发布时间、发布单位
#爬取网页
url
=
"https://www.bilibili.com/read/cv1119650?from=search"
res
=
requests.get(url)
type
(res)
res.encoding
=
"utf-8"
soup1
=
BeautifulSoup(res.text,
'html.parser'
)
time
=
soup1.select(
'.create-time'
)
au
=
soup1.select(
'.author-name'
)
title
=
soup1.select(
'.title'
)
print
(time,
'\n'
,au,
'\n'
title)
1
|
simple = open (r 'C:\Backup\桌面\index.html' , 'r' ,encoding = 'utf-8' ) |
simpleR = simple.read()
soup=BeautifulSoup(simpleR,'html.parser')
1
2
3
4
|
h = soup.select( 'h1' ) id = soup.select( '#from1' ) cls = soup.select( '.AD' ) print (h, id , cls ) |