Python爬蟲小試——爬取圖片
阿新 • • 發佈:2018-12-13
如果是直接裝了Anaconda整合開發環境的,就可以直接移步原始碼了
否則的話,在爬取圖片之前要安裝幾個包
第一個:bs4
包,需要用到其中的BeautifulSoap,是一個功能強大的網頁解析工具
pip3 install bs4
第二個:requests
包,安裝步驟如上,用於抓取網頁原始碼
程式碼如下:
import requests,os
from bs4 import BeautifulSoup
from urllib.request import urlopen
images_dir = "images/" #要儲存的資料夾
if not os.path.exists(images_dir) :
os.mkdir(images_dir)
url = "http://www.baidu.com/" #url
html = requests.get(url) #獲取html文字
html.encoding = 'utf-8' #編碼格式utf-8
sp = BeautifulSoup(html.text,'html.parser') #原始碼解析
links = sp.find_all(["img",'a']) #找出所有img標籤
index = 0
for link in links:
src = link. get('src') #獲取src
if src != None and 'https' in src: #非空src
if 'jpg' in src:
img_name = str(index+1) + ".jpg"
elif 'png' in src:
img_name = str(index+1) + ".png"
image = urlopen(src) #url open
f = open(os.path.join( images_dir,img_name),"wb") #建立檔案
f.write(image.read()) #寫入圖片
f.close()
print('%d finish\n'%(index+1))
index = index + 1
print("OK")