Python 簡易爬蟲教學

SheiUn
SheiUn
Sep 4, 2018 · 5 min read

想要不開網頁也能看到資料嗎?

前置作業

  • 安裝 Python3+

開始囉~

  1. 打開 Command Line Interface
Windows: Win + RUbuntu: Ctrl + Alt + T

2.新增一個資料夾並進入

mkdir crawler-demo && cd crawler-demo

3.安裝虛擬環境 (如果你不在意本機的環境有多髒亂可以跳過這一步)

Windows: pip install virtualenv
Ubuntu: sudo apt-get install virtualenv

把虛擬環境建置在此資料夾

virtualenv env -p python3 (這邊的 python3 對應到你平常用的 python3)

進入虛擬環境

Windows: env\Scripts\activate
Ubuntu: . env/bin/activate

4.安裝爬蟲套件

請注意你的 pip 版本 輸入 pip -V 版本是 3以上才是正確的喔

pip install requests

5.用文字編輯器打開寫程式的檔案

Windows: notepad demo.py // 你也可以用別的文字編輯器
Ubuntu: nano demo.py // 菜雞如我只會用 nano

6.開始寫程式

以下為 demo.py 檔案內容

import requests  # 引入 requests 模組url = 'https://network.ntust.edu.tw/'  # 台科的流量查詢網站
res = requests.get(url) # 對這個網站發送一個 GET 請求並將回傳的值指派給 res(response 的縮寫)
print(res, res.text) # 將 res 和 res.text 打印出來

儲存(記得檔案格式存成 UTF-8)後

CLI 執行python demo.py

這樣子你就能看到 網頁的原始碼了

res 通常會是一個 status code 200 代表成功 404 代表找不到…

res.text 則是網頁原始碼的部分

7.萃取有效資訊

首先你必須知道你要的資訊有哪些,以這個流量統計網站為例
最主要的資訊就是總流量,所以打開 網頁 > 檢查 (Chrome是 Ctrl+Shfit+I)

先選擇 Networks 然後點選 XHR重新整理 確認這個網頁的運行方式

因為有的網頁是透過 javascript 再把資料塞進去

這個就沒辦法用簡單的方法把資料抓出來

這個時候看到有一個 getFlowData 的請求

先看一下 Header 再看一下 Response

發現他就是透過這個 url 去做資料的存取注入
實在是不太應該啊 正常來講應該要把這種東西包在後端才對
不過沒關係 這樣反而更好爬

接下來就是對這個 url 直接的請求

https://network.ntust.edu.tw/flowStatistics/getFlowData

在發送請求之前 要先了解他是用什麼方法送請求的

既然是 POST 那就一定會有 payload 所以往下滑

所以我們只要把這行複製下來 存到 payload 裡面用 post 請求就能拿到資料了

import requests
url = 'https://network.ntust.edu.tw/flowStatistics/getFlowData'
res = requests.post(url, data={"ip":"140.118.149.163","dt":"2018-09-03T16:00:00.000Z","units":"1"}) # 直接複製貼上
print(res.text)

最後一樣執行 python demo.py 就能看到以下結果

8.解析拿到的資料

這個的資料型態是 json 是一個在網路上很常拿來用的格式

所以 Python 也有相應的函式庫可以使用

import json
data = json.loads(res.text)

但是我們最終是要取得總流量所以要看一下他的位置在哪

發現在 items > 第一個元素 > totflow

print(data['items'][0]['totflow'])

無用的爬蟲 就是這麼的簡單

sheiun

雪煾的日常生活

SheiUn

Written by

SheiUn

I’m studying Management of Information System in NTUST. I love to study many kinds of books. And watch some science channel.

sheiun

sheiun

雪煾的日常生活

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade