首页 > 其他 > 详细

理解爬虫原理

时间:2019-03-25 20:07:32      阅读:190      评论:0      收藏: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)

 



理解爬虫原理

原文:https://www.cnblogs.com/huangjianke123/p/10592835.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!