代码改变世界

理解爬虫原理

2019-03-25 19:54  科ke  阅读(176)  评论(0编辑  收藏  举报

1. 简单说明爬虫原理

发起请求:通过HTTP库向目标站点发起请求,即发送一个Request,请求可以包含额外的headers等信息,等待服务器响应。
获取响应内容:如果服务器能正常响应,会得到一个Response,Response的内容便是所要获取的页面内容,类型可能有HTML,Json字符串,二进制数据(如图片视频)等类型。
解析内容:得到的内容可能是HTML,可以用正则表达式、网页解析库进行解析。可能是Json,可以直接转为Json对象解析,可能是二进制数据,可以做保存或者进一步的处理。
保存数据:保存形式多样,可以存为文本,也可以保存至数据库,或者保存特定格式的文件。

 

2. 理解爬虫开发过程

1).简要说明浏览器工作原理;

  • 域名解析 
  • 发起TCP的3次握手 
  • 建立TCP连接后发起http请求 
  • 服务器响应http请求,浏览器得到html代码 
  • 浏览器解析html代码,并请求html代码中的资源(如js、css、图片等) 
  • 浏览器对页面进行渲染呈现给用户

 

2).使用 requests 库抓取网站数据;

requests.get(url) 获取校园新闻首页html代码

import requests
from bs4 import BeautifulSoup

url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
res = requests.get(url)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
print(soup);

3).了解网页

写一个简单的html文件,包含多个标签,类,id

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <style type="text/css">
    .head {
        margin-top: 50px;
        font-size: 30px;
        color: red;
    }
    #body {
        font-size: 20px;
        color: blue;
        margin-top: 50px;
    }

    </style>
</head>
 
<body>
<center>
<div class="head">
    广州商学院
</div>
    <div id="body">
        用户名:<input type="text"><br>
        密码:<input type="text">
    </div>
</center>

</body>
 
</html>

 

4).使用 Beautiful Soup 解析网页;

通过BeautifulSoup(html_sample,'html.parser')把上述html文件解析成DOM Tree

select(选择器)定位数据

找出含有特定标签的html元素

找出含有特定类名的html元素

找出含有特定id名的html元素

from bs4 import BeautifulSoup

htmlfile = open('bbb.html', 'r', encoding='utf-8')
htmlhandle = htmlfile.read()
soup = BeautifulSoup(htmlhandle, "html.parser");

# 找出含有特定标签的html元素
print(soup.select("input"));
# 找出含有特定类名的html元素
print(soup.select(".head"));
# 找出含有特定id名的html元素
print(soup.select("#body"));

 

3.提取一篇校园新闻的标题、发布时间、发布单位

url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html'

 

 

 

import requests
from bs4 import BeautifulSoup

url = 'http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0401/9167.html'
res = requests.get(url)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
aa=soup.select('.show-title')[0].text
bb=soup.select('.show-info')[0].text
print(aa+'\n')
print(bb+'\n')