"""
問題:用 Python 寫一個爬圖片的程序
常用庫:BeautifulSoup
"""
from bs4 import BeautifulSoup
import urllib.request
from os.path import dirname, exists
from os import makedirs
# 獲取圖片的url連接
def getImg(url):
htmlsource = urllib.request.urlopen(url).read()
bs = BeautifulSoup(htmlsource, "html.parser")
imglist = bs.find_all('img', attrs={"class": "origin_image"})
for i in range(len(imglist)):
link = imglist[i]
download(link.get('data-original'))
# 保存到本地
def download(url):
print(url)
file = 'd://爬蟲/知乎壁紙' + url[url.rindex('/'):]
# 文件處理
ldir = dirname(file)
if not exists(ldir):
makedirs(ldir)
urllib.request.urlretrieve(url, file)
if __name__ == '__main__':
getImg('https://www.zhihu.com/question/24340705')
Show me the code之Python練習冊 Q13 獲取網絡圖片
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.