# python_爬蟲菜雞入門 :fire:X1 ## 前言 如何擷取網頁資料做出資料分析 爬蟲主要分兩種 1.Api 人家寫好規則,按照參數就可以 2.網站 寫好規則,依據網站架構撰寫 ## 步驟 :::warning 網頁爬蟲與資料分析可以分成以下步驟 ::: 1. 請求 2. 解析 3. 儲存 4. 造訪下一頁 ## 1.請求 * 通過url對server發送請求,server收到請求後進行處理和解析,回傳訊息 ```sequence Client->Server: Requests Server->Client: Resopnse ``` * 如果成功,回傳相應的網頁資料 * 狀態代碼 狀態描述 說明: | status code | status description | status content | | -------- | -------- | -------- | | 200 | ok | 客戶端請求成功 | | 400 | Bad Request | 由於客戶端請求有語法錯誤,不能被伺服器所理解 | | 403 | Forbidden | 伺服器收到請求,但是拒絕提供服務。伺服器通常會在響應正文中給出不提供服務的原因 | | 404 | Not Found | 請求的資源不存在,例如,輸入了錯誤的URL。 | * 常見的請求方法: * get * post(適合用於隱密性較高的資料) | Http請求方法 | 舉例 | | -------- | -------- | | Get | 跟Server拿東西 | | Post | 向Server丟東西 | * [政府開放平台_即時水位資料api抓取測試](https://github.com/Lukaka4331/python_crawler/blob/master/government_api_test/python_api_crawl_test.ipynb) ## 2. 解析 * Beautiful Soup :bulb:對新手比較友善的爬蟲模組,如果只是單純要抓點網頁,或是練習爬蟲,建議可以從這個起手 #常用的函數-find(),find_all() find(tag, attribute, recursive, text, keywords) find_all(tag, attribute, recursive, text, keywords) * [正則表達式 (regular expression)](https://hackmd.io/FgpVLKvaRiuekdxTvln8Ig) 結合(beautiful soup + regular expression): >[food panda (beautiful soup + regular expression)](https://github.com/Lukaka4331/python_crawler/blob/master/beautifulsoup_v1.ipynb) * 參考資料 >[Python 使用 requests 模組產生 HTTP 請求,下載網頁資料教學 ](https://blog.gtwang.org/programming/python-requests-module-tutorial/) >[Python 使用 Beautiful Soup 抓取與解析網頁資料,開發網路爬蟲教學 ](https://blog.gtwang.org/programming/python-beautiful-soup-module-scrape-web-pages-tutorial/) >[python append()與extend()的差別 ](https://hackmd.io/@Hh_agMATRciWBNEnBwNQtQ/rJpqxp5KI) ## 3. 儲存 * tools: pandas :::success * pandas是一個基於 numpy 的函式庫,不論是用來 讀取、處理數據都非常的簡單方便 * 處理結構化的數據非常好用! ::: * DataFrame 是由 rows 跟 columns 所組成的一個 大表格 ![](https://i.imgur.com/MeZ95uz.jpg) * 常用的資料格式‐ CSV * 欄位間的資料用逗號作分隔 * 參考資料: [pandas神講解](https://leemeng.tw/practical-pandas-tutorial-for-aspiring-data-scientists.html) ## 4. 造訪下一頁 * 頁數 - 總共幾頁 * 網頁 - 網址變化 * 迴圈執行 * [交通部觀光局](https://www.taiwan.net.tw/m1.aspx?sNo=0000064&page=1) >https://www.taiwan.net.tw/m1.aspx?sNo=0000064&page=1 觀察網頁的變化: >所以能夠知道變化的數字是跳頁的原因 ```python= import requests from bs4 import BeautifulSoup import pandas as pd import re from tqdm.notebook import tqdm pagenum=63 pageurl = 'https://www.taiwan.net.tw/m1.aspx?sNo=0000064&page={}' for page in tqdm(range(pagenum)): resp = requests.get(pageurl.format(page+1)) soup = BeautifulSoup(resp.text, 'lxml') for tourist_url in soup.find("ul",{"class":"grid card-list card-style-columns"}).find_all("a",{"class":"card-link"}) : Url="https://www.taiwan.net.tw/" + tourist_url.get('href') data_dict['Location_URL'].append(Url) print(Url) ``` ###### tags: `python_crawing`