iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 24
2
Modern Web

🍐放學後的網頁開發系列 第 24

[Day24] 柚子放學後的網頁生活 - Web Crawler

  • 分享至 

  • xImage
  •  

今天來換換口味,算是個小插曲加預告XD
下篇再繼續我們的照片分享網誌~~
( 只剩 Post 文章就完成了 ! )

Web Crawler

Q:網頁爬蟲是什麼:

爬蟲是一個將網路上的檔案下載下來然後處理、資料分析的程式,我們在網路上看到的網頁、圖片或影片等,都算是一個檔案,只是透過瀏覽器變成我們看到的結果 ~

Q:這要幹嘛 !?

一定會有人想說爬別人網頁幹嘛XD,那我說我覺得最有價值的好了~~
爬股票、財報,我們可以用這些資料做量化分析,雖然過去績效不等於未來,但也是有一點點參考價值哦 ~

Use Requests model

我們會用到的工具 - Request
Requests模組功能:可以用來讀取網頁原始碼,再藉由正規表達式取得符合資料
直接來抓個網頁就知道了,我以我的目錄頁為範例

import requests
url ='https://ithelp.ithome.com.tw/users/20111479/ironman/1790'
html = requests.get(url)
print(html.text)

我們看他print出什麼呢 ...

用以上這段程式碼就可以抓取我的主頁HTML,可再另外加上 html.status_code == 200的條件加以判斷伺服器傳回來的狀態碼沒問題再print,做加一步的檢查

自訂HTTP Headers:
Headers 為請求和回應的核心,包含User的瀏覽器、請求頁面、server等資訊,自訂Headers可用程式模擬瀏覽器操作,避過網頁檢查

發送POST請求:

  1. 當網頁中有表單要請User key in,大部分需用POST來進行傳送(少數GET)
  2. 經常需加入查詢參數,後面會以payload示範

Session / Cookie:
憑證儲存在User端的瀏覽器為Cookie,產生在Server端的為Session
(可以以requests.Session()為網站建立Session)

好那我們來個小挑戰 ...

嘗試進入Gossip版​

進入PTT Gossip版抓取網頁資料前,需要按同意的BUTTON,那怎麼辦 ?

製造一個假的通過方式騙騙它 ...

import requests
from bs4 import BeautifulSoup
payload = {
'from': 'https://www.ptt.cc/bbs/Gossiping/index.html',
'yes': 'yes'
#按我同意 button的value設yes
}
headers = {
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
}
rs = requests.Session()
rs.post('https://www.ptt.cc/ask/over18', data=payload, headers=headers)
#成功進入後再Get頁面
res = rs.get('https://www.ptt.cc/bbs/Gossiping/index.html', headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
items = soup.select('.r-ent')
for item in items:
#單純印text
    print(item.select('.date')[0].text, item.select('.author')[0].text, item.select('.title')[0].text)

還有一個很常用的package ~~

Beautifulsoup

Beautiful Soup 讓開發者撰寫非常少量的程式碼,就可以快速解析網頁 HTML 碼,再應由寫好的功能去抽取想要的HTML Tag,就可以進行網頁解析、資料分析囉 ~

那為了省麻煩,我這邊建一個html變數來塞HTML該有的東西

html = """
<html><head><title>網頁標題</title></head>
<p class="header"><h2>文件標題</h2></p>
<div class="content">
<div class="item1">
<a href="http://example.com/one" class="red" id="link1">First</a>
<a href="http://example.com/two" class="green" id="link2">Second</a>
</div>
</div>
"""

那接著就可以來 import 這次的工具囉 ~
注意:對應的tag以 . 來抓!

from bs4 import BeautifulSoup
sp = BeautifulSoup(html,'html.parser')
print("--sp.title--") 
print(sp.title)
print("------------")
print("--sp.find('h2')--")
print(sp.find('h2'))
print("------------")
print("--sp.find_all('a')--")
print(sp.find_all('a'))
print("------------")
print("--針對class為red--")
print(sp.find_all("a", {"class":"red"}))
print("------------")
print("--依href做find--")
data1=sp.find("a", {"href":"http://example.com/one"})
print(data1.text) # First
print("------------")

在後面會帶大家抓抓看股票、做簡單的資料分析哦
可以期待一下XD

下課囉 ~ 請鎖定 柚子放學後的網頁生活


上一篇
[Day23] 柚子放學後的網頁生活 - Django 前後端分離
下一篇
[Day25] 柚子放學後的網頁生活 - Django Photo sharing
系列文
🍐放學後的網頁開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言