* 使用 Python 的 Requests 和 Beautiful Soup 函式庫,實作一個可以自動下載圖片的網路爬蟲 * PTT Beauty 板網址:https://www.ptt.cc/bbs/Beauty/index.html * 安心亞照片分享網址:https://www.ptt.cc/bbs/Beauty/M.1638380033.A.7C7.html ``` import requests from bs4 import BeautifulSoup web = requests.get('https://www.ptt.cc/bbs/Beauty/M.1638380033.A.7C7.html', cookies={'over18':'1'}) # 傳送 Cookies 資訊後,抓取頁面內容 soup = BeautifulSoup(web.text, "html.parser") # 使用 BeautifulSoup 取得網頁結構 imgs = soup.find_all('img') # 取得所有 img tag 的內容 for i in imgs: print(i['src']) # 印出 src 的屬性 ```  * 讀取並下載圖片 ``` import requests from bs4 import BeautifulSoup web = requests.get('https://www.ptt.cc/bbs/Beauty/M.1638380033.A.7C7.html', cookies={'over18':'1'}) # 傳送 Cookies 資訊後,抓取頁面內容 soup = BeautifulSoup(web.text, "html.parser") # 使用 BeautifulSoup 取得網頁結構 imgs = soup.find_all('img') # 取得所有 img tag 的內容 name=0 for i in imgs: print(i['src']) jpg = requests.get(i['src']) # 使用 requests 讀取圖片網址,取得圖片編碼 f = open(str(name)+".jpg", 'wb') # 使用 open 設定以二進位格式寫入圖片檔案 f.write(jpg.content) # 寫入圖片的 content f.close() # 寫入完成後關閉圖片檔案 name = name + 1 ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up