作業來源: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)