Try   HackMD

輕鬆學會程式交易 | Chapter 4 | 取得資料

4-2 初階爬蟲教學

爬蟲步驟

setp1 分析

  1. 找到網頁,滑鼠右鍵點選“檢查”
  2. 點擊”network”(網絡面板)版面
  • 功能:網絡面板功能:找到下載的文件
  1. 點選priview,在Name裡面的檔案尋找我們要的資訊
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →
  2. 點選Headers,觀察欄位
  • General(一般資訊)

    • RequestURL:伺服器請求的網址
    • Request Method:伺服器傳送訊息的方式
  • Request Headers(請求標頭)

    • 功能:用戶端流覽器,請求頁面的時候,它的行為或狀態的相關資訊
    • User-Agent:假裝自己是瀏覽器,因為User-Agent會告訴網站它是透過什麼工具(瀏覽器名稱、瀏覽器版本號、渲染引擎、操作系統)發送請求的,就可以騙過該網站了
  • Form Data(表單數據)

    • 功能:填入post表單的資料
  • Query String Parameters(查詢參數)

    • 功能:用GET方法的時候填入的參數

setp2 數據處理

  1. 使用BeautifoulSoup或pandas解析數據

Requests套件

Requests是一個實現HTTP請求的工具,可以模仿瀏覽器,取得網路端的信息。

pip install requests

範例

我們使用這個網址來做示範,點進去即可看到現在電腦的IP。

url = "http://www.j4.com.tw/james/remoip.php" res = requests.get(url) print(res.text)
'<html>\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<title>查看自己的IP</title>\n<link rel=stylesheet type="text/css" href="test.css">\n</head>\n\n<body>\n<p>&nbsp;</p>\n<div align="center">\n<h2>查看自己的IP</h2>\n您的 IP 是: xxxx.xxxxx.xxxx.xxxx<br><br><br><br>\n<a href="/">HOME</a>\n</div>\n</body>\n</html>\n'