一、簡單說明爬蟲原理
通俗來講,網絡爬蟲是指通過程式模拟浏覽器站點的行為,向網站發起請求,把站點傳回的HTML代碼、JSON資料、二進制資料(圖檔、視訊等)抓取到本地,再通過程式提取分析資料,用以代替繁瑣、低效和通過複制粘貼等手段來擷取資料的技術。

二、了解爬蟲開發過程
1、簡要說明浏覽器工作原理
使用者在浏覽器輸入url,浏覽器向web伺服器發送request請求,伺服器收到請求并處理後向浏覽器傳回response,然後浏覽器通過解析response講結果呈現給使用者。在這個過程中,浏覽器是可以通過爬蟲分析資料的(部分網站不允許)。
2、使用requests庫抓取網站資料
import requests
url='http://news.gzcc.cn/html/xiaoyuanxinwen/'
res = requests.get(url)
print("status_code = {}".format(res.status_code))#狀态字
type(res)
res.encoding='utf-8'#編碼格式
print(res.text)
3、了解網站
編寫一個簡單的網頁:
html_sample='''
<html>
<head>
<title>這是标題</title>
</head>
<body>
<div>
<p>這是段落<p><br>
<a href="http://www.gzcc.cn" >廣州商學院</a>
</div>
</body>
</html>
'''
網站的基本工作原理:浏覽器根據源代碼,解析DOM樹,進行樣式渲染,最後将結果傳回給使用者:
4、使用BeautifulSoup解析網頁
BeautifulSoup是HTML/XML的解析器,主要是來解析整個DOM樹,它提供了簡單有常用懂得導航、搜尋、以及修改結構樹的操作,可以提高提取資料的效率。
(1) 解析标簽對象屬性:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_sample,'html.parser')
print(soup.head)
print('-------------------------')
print(soup.head.text)
print('-------------------------')
print(soup.p.contents)
print('-------------------------')
print(soup.p.name)
(2) select選擇定位資料:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_sample,'html.parser')
print(soup.select('h1'))#選擇h1标簽
print(soup.select('.p1'))#選擇類為p1元素
print(soup.select('#btn'))#選擇id為btn的元素
三、提取一篇校園新聞的标題、釋出時間、釋出機關
import requests
from bs4 import BeautifulSoup
url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html'
res = requests.get(url)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
print("标題:{}\n釋出時間、釋出機關: {}".format(soup.select('.show-title')[0].text, soup.select('.show-info')[0].text))