1. 環(huán)境準備
1.1 安裝python
1.2 安裝pip: easy_install pip
1.3 安裝requests庫:python -m pip install requests
1.4 eclipse安裝pydev插件
2. 過程
主要用到urllib中的request模塊,請求目標地址,并將獲取到的內(nèi)容解碼成HTML,然后通過正則匹配獲取圖片的地址,最后通過urlretrieve方法將獲取到的圖片下載到本地
3. 代碼部分
#!/usr/local/bin/python3.6
# encoding: utf-8
from urllib import request
import re
def main():
# 獲取網(wǎng)頁并解碼
response = request.urlopen("https://www.douban.com/photos/album/1652957514/");
html = response.read()
html = html.decode("utf-8")
# 正則匹配圖片,獲取圖片地址的list,正則中()是最終需要匹配返回的內(nèi)容
reg = '<img\swidth="\d+"\ssrc="(https://img3.doubanio.com[/\w\.]*)'
imgre = re.compile(reg)
imgs = re.findall(imgre, html)
# 將圖片下載到本地,由于獲取到的某些地址無法訪問會有報錯,因此此處需要catch一下異常
x=0
for img in imgs:
# print(img)
try:
request.urlretrieve(img, 'C:\work\Python\spider\%s.gif' % x)
# request.urlopen(img)
x += 1
except Exception as e:
print(e)
if __name__ == '__main__':
main()
參考
以上內(nèi)容只是個人練習(xí)記錄,參考以下博客,博客內(nèi)容更加詳細
https://blog.csdn.net/cloudox_/article/details/53465923
https://blog.csdn.net/c406495762/article/details/58716886