###### tags: `web crawler`,`網路爬蟲` # web crawler 實作--查找金石堂特價書籍與價格 ```python= import requests from bs4 import BeautifulSoup #查找user-agent網址,每個電腦都不一樣喔 #打上此網址http://httpbin.org/user-agent,把自己專屬的複製貼到程式碼第11行後面雙引號裡即可 myHead={"user-agent": "Mozilla/5.0 <<後面省略>>"} urL="https://www.kingstone.com.tw" #金石堂網站網址 #測試有傳headers有無差別 r1=requests.get(urL) print("沒傳headers的status_code: ",r1.status_code)#結果指向用戶端錯誤 print("=====================================================") r2=requests.get(urL,headers=myHead) print("傳送headers的status_code: ",r2.status_code)#成功回應 #遇到某些網站會檢查Client端是否為[正常]連線而非爬蟲程式時 #你必須送出你的[hearders]偽裝成[正常連線] ``` ![](https://i.imgur.com/0ScGIoE.png) **HTTP 狀態碼** HTTP 狀態碼表明一個 HTTP 要求是否已經被完成。 回應分為五種: 1. 資訊回應 (Informational responses, 100–199) 2. 成功回應 (Successful responses, 200–299) 3. 重定向 (Redirects, 300–399) 4. 用戶端錯誤 (Client errors, 400–499) 5. 伺服器端錯誤 (Server errors, 500–599) 金石堂網頁按右鍵點選檢查 即可開始解析網頁,目標為查找下圖紅框書名、價格與超連結 可以先以"ul" & "li"做初步定位 ![](https://i.imgur.com/pMqd4oz.png) ![](https://i.imgur.com/ea7Y60w.png) ![](https://i.imgur.com/Vta8k9n.png) ```python= import requests from bs4 import BeautifulSoup myHead={"user-agent": "Mozilla/5.0 <<後面省略>>"}#如上說明 urL="https://www.kingstone.com.tw" rq=requests.get(urL,headers=myHead).text #要記得送headers soup=BeautifulSoup(rq,"html5lib")#透過html5lib解析網頁 soup2=soup.find("ul","gallerytopcol clearfix") #1st定位 for mysoup in soup2.find_all("li"):#2次定位,把隸屬於ul這層的li都找出來,使用find_all print(mysoup.h3.a.text) #書籍名稱在h3裡面 print(mysoup.find_all("b")[1].text) #抓價格 # print(mysoup.h3.a["href"]) #此方式抓連結為簡寫 print("https://www.kingstone.com.tw"+mysoup.h3.a["href"])#自己加上官網網址 print("*******************") ``` ![](https://i.imgur.com/dllrVIS.png) **HTML 語法** 基本上項目清單的 HTML 語法有兩種: 一類是 ul 也就是沒有數字排序的清單(Unordered List) 一類是 ol 有數字編號排序的清單(Ordered List)