本次做業要求來自於:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2881php
1. 簡單說明爬蟲原理html
經過程序模擬瀏覽器請求站點的行爲,發送請求,得到響應,對響應的網頁代碼進行解析提取本身須要的數據,存儲到數據庫中以供使用。數據庫
2. 理解爬蟲開發過程api
1).簡要說明瀏覽器工做原理;瀏覽器
用戶經過瀏覽器搜索進行發送請求,服務器把符合的響應傳給用戶,瀏覽器得到響應後,對響應的網頁代碼進行解析渲染呈現內容給用戶。服務器
2).使用 requests 庫抓取網站數據;網站
例:用requests.get(url) 獲取校園新聞首頁html代碼url
import requests url='http://www.gzcc.cn/index.html' res = requests.get(url) res.encoding='utf-8' res.text
運行示例:spa
3).瞭解網頁code
寫一個簡單的html文件,包含多個標籤,類,id
4).使用 Beautiful Soup 解析網頁;
經過BeautifulSoup(html_sample,'html.parser')把上述html文件解析成DOM Tree
select(選擇器)定位數據
找出含有特定標籤的html元素
找出含有特定類名的html元素
找出含有特定id名的html元素
import bs4 from bs4 import BeautifulSoup html_sample = ''' <html> <body> <h1 id="title">Hello</h1> <a href="#" class="link"> This is link1</a> <a href="# link2" class="link" id="link2"> This is link2</a> </body> </html> ''' soups = BeautifulSoup(html_sample,'html.parser') print(soups.h1.text) print(soups.select('a')) print(soups.select('.link')[0].text) print(soups.select('#link2')[0].text)
運行示例:
3.提取一篇校園新聞的標題、發佈時間、發佈單位、做者、點擊次數、內容等信息
如url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0323/11052.html'
要求發佈時間爲datetime類型,點擊次數爲數值型,其它是字符串類型。
# 導入requests,獲取指定網頁的html文件 import requests url='http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0323/11052.html' res = requests.get(url) res.encoding='utf-8' # 導入bs4中的BeautifulSoup,用來解析網頁的html from bs4 import BeautifulSoup soupTest=BeautifulSoup(res.text,'html.parser') # 解析得到對應的內容 title = soupTest.select('.show-title')[0].text editInfo = soupTest.select('.show-info')[0].text.split() date = editInfo[0].split(':')[1] time = editInfo[1] releaseTime = date + ' ' +time # 導入datetime類,用於把字符串轉換成時間 from datetime import datetime releaseTime = datetime.strptime(releaseTime,'%Y-%m-%d %H:%M:%S') author = editInfo[2] auditor = editInfo[3] photographer = editInfo[5] source = editInfo[4] newsContent = soupTest.select('.show-content')[0].text.strip() # 解析對應文件得到想要的內容 clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id=11052&modelid=80' clickStruct = requests.get(clickUrl).text clickCount = int(clickStruct.split('.html')[-1][2:-3]) # 輸出提取的一篇校園新聞的標題、發佈時間、發佈單位、做者、點擊次數、內容等信息 print('校園新聞的標題:',title,'\n發佈時間:',releaseTime,'\n',source,'\n',author,'\n',photographer,'\n點擊次數:',clickCount) print('內容主要有:',newsContent)
運行示例: