python爬蟲beautifulsoup4系列3【轉載】

來源:互聯網
上載者:User

標籤:對象   電腦   tool   coding   lis   list   技術分享   方法   log   

本篇轉自部落格:上海-悠悠

原文地址:http://www.cnblogs.com/yoyoketang/tag/beautifulsoup4/

前言

本篇手把手教大家如何爬取網站上的圖片,並儲存到本地電腦

 

一、目標網站

1.隨便開啟一個風景圖的網站:http://699pic.com/sousuo-218808-13-1.html

2.用firebug定位,開啟firepath裡css定位靶心圖表片

3.從可以看出,所有的圖片都是img標籤,class屬性都是lazy

 

二、用find_all找出所有的標籤

1.find_all(class_="lazy")擷取所有的圖片對象標籤

2.從標籤裡面提出jpg的url地址和title

 1 # coding:utf-8 2 from bs4 import BeautifulSoup 3 import requests 4 import os 5 r = requests.get("http://699pic.com/sousuo-218808-13-1.html") 6 fengjing = r.content 7 soup = BeautifulSoup(fengjing, "html.parser") 8 # 找出所有的標籤 9 images = soup.find_all(class_="lazy")10 # print images # 返回list對象11 12 for i in images:13     jpg_rl = i["data-original"]  # 擷取url地址14     title = i["title"]           # 返回title名稱15     print title16     print jpg_rl17     print ""

 

三、儲存圖片

1.在當前指令檔夾下建立一個jpg的子檔案夾

2.匯入os模組,os.getcwd()這個方法可以擷取當前指令碼的路徑

3.用open開啟寫入本地電腦的檔案路徑,命名為:os.getcwd()+"\\jpg\\"+title+‘.jpg‘(命名重複的話,會被覆蓋掉)

4.requests裡get開啟圖片的url地址,content方法返回的是二進位流檔案,可以直接寫到本地

 

四、參考代碼

 1 # coding:utf-8 2 from bs4 import BeautifulSoup 3 import requests 4 import os 5 r = requests.get("http://699pic.com/sousuo-218808-13-1.html") 6 fengjing = r.content 7 soup = BeautifulSoup(fengjing, "html.parser") 8 # 找出所有的標籤 9 images = soup.find_all(class_="lazy")10 # print images # 返回list對象11 12 for i in images:13     jpg_rl = i["data-original"]14     title = i["title"]15     print title16     print jpg_rl17     print ""18     with open(os.getcwd()+"\\jpg\\"+title+‘.jpg‘, "wb") as f:19         f.write(requests.get(jpg_rl).content)

python爬蟲beautifulsoup4系列3【轉載】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.