python介面自動化測試十八:使用bs4架構爬取圖片

來源:互聯網
上載者:User

標籤:解析   name   地址   pytho   for   not   簽名   技術分享   imp   

# 爬圖片
# 目標網站:http://699pic.com/sousuo-218808-13-1.html
import requests
from bs4 import BeautifulSoup
import os
r = requests.get(‘http://699pic.com/sousuo-218808-13-1.html‘)

# r.content # 返回的是位元組流

soup = BeautifulSoup(r.content, ‘html.parser‘) # 用html解析器,尋找r.content

# tu = soup.find_all(‘img‘) # 尋找所有的標籤名字為“img”的對象
tu = soup.find_all(class_="lazy") # 尋找所有的標籤名字為“class_="lazy"”的對象


for i in tu:
# print(i)
# <img alt="洱海清晨的彩霞倒映水中高清圖片" class="lazy" data-original="http://img95.699pic.com/photo/50061/5608.jpg_wh300.jpg" height="300" src="http://static.699pic.com/images/blank.png" title="洱海清晨的彩霞倒映水中圖片下載" width="453.30915684497"/>
print(i[‘data-original‘]) # 擷取所有的url地址

# 爬單張圖片
url = ‘http://img95.699pic.com/photo/50061/5608.jpg_wh300.jpg‘
r = requests.get(url)
f = open(‘123.jpg‘, ‘wb‘) # 以二進位寫入的方式開啟一個名為123.jpg的檔案 (尾碼可隨意改)
f.write(r.content) # 把r傳輸的位元組流寫入到檔案中
f.close() # 關閉檔案

 



# 批量寫入:

# 建立路徑, 建立一個名為“tupian”的檔案夾
curpath = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
tupian = os.path.join(curpath, ‘tupian‘)
if not os.path.exists(tupian): # 判斷名字為“tupian”的檔案夾是否為不存在
os.mkdir(tupian) # 不存在,則建立名字為“tupian”的檔案夾
# 批量寫入圖片並儲存
for i in tu:
try:
jpg_url = i[‘data-original‘] # 要擷取的圖片的地址
name = i[‘alt‘]
r = requests.get(jpg_url)
# 寫入內容,放到tupian檔案夾下
f = open(os.path.join(tupian, ‘%s.jpg‘%name), ‘wb‘)
f.write(r.content)
f.close()
except:
pass

 

 

 

 


python介面自動化測試十八:使用bs4架構爬取圖片

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.