理解爬虫原理

作业来源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2881

一. 简单说明爬虫原理

  爬虫即是从网络中爬取数据,就python为例,利用requests模块访问网址,将访问后返回的html保存下来,并利用bs4进行分析,将想要的数据保存下来。

二. 理解爬虫开发过程

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

  从用户键入网址回车确认后,浏览器向服务器发送http请求,服务器接收到请求后相应的业务逻辑处理,并返回数据,浏览器接收到数据后,便开始解析返回来的数据,并生成DOM模型,渲染界面。

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

  运行代码:

get=requests.get('http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0328/11086.html')
get.encoding='utf-8'
print(get.text)

  运行效果:

 

3.了解网页

  运行代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="header">
    <button name="first_btn"></button>
</div>

<div class="main-contain">
    <table>
        <tr>
            <td>id</td>
            <td>姓名</td>
            <td>年龄</td>
        </tr>
    </table>
</div>

<div class="footer">

</div>
</body>
</html>

  

4.使用 Beautiful Soup 解析网页

  运行代码:

import bs4
from bs4 import BeautifulSoup
get=requests.get('http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0328/11086.html')
get.encoding='utf-8'
soup=BeautifulSoup(get.text,'html.parser')

  

三.提取一篇校园新闻的标题、发布时间、发布单位、作者、点击次数、内容等信息

  运行代码:

import requests
import bs4
from bs4 import BeautifulSoup
from datetime import datetime
import re
get=requests.get('http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0328/11086.html')
get.encoding='utf-8'
soup=BeautifulSoup(get.text,'html.parser')
title=soup.select('.show-title')[0].text;
head=soup.select('.show-info')[0].text.split()
datetime=datetime.strptime(head[0][5:]+" "+head[1],'%Y-%m-%d %H:%M:%S')
time = re.findall("\d+",requests.get('http://oa.gzcc.cn/api.php?op=count&id=11086&modelid=80').text.split(';')[3])[0]
content=soup.select('.show-content')[0].text
print('标题:'+title)
print('发布时间:'+str(datetime))
print(head[4])
print(head[2])
print('点击次数:'+time)
print(content)

  运行效果:

 

posted @ 2019-03-30 10:54  97lzc  阅读(163)  评论(0编辑  收藏  举报