一、選取網址進行爬蟲
本次我們選取pixabay圖片網站
1
|
url = https: / / pixabay.com / |
二、選擇圖片右鍵選擇查看元素來尋找圖片鏈接的規則
通過查看多個圖片路徑我們發現取src路徑都含有 https://cdn.pixabay.com/photo/ 公共部分且圖片格式都為.jpg 因此正則表達式為
1
|
re. compile (r '^https://cdn.pixabay.com/photo/.*?jpg$' ) |
通過以上的分析我們可以開始寫程序了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
#-*- coding:utf-8 -*- import re import requests import os from bs4 import beautifulsoup url = 'https://pixabay.com/' html = requests.get(url).text #獲取網頁內容 print (html) # 這里由于有些圖片可能存在網址打不開的情況,加個5秒超時控制。 #data-objurl="http://pic38.nipic.com/20140218/17995031_091821599000_2.jpg"獲取這種類型鏈接 soup = beautifulsoup(html, 'html.parser' ,from_encoding = 'utf-8' ) #^abc.*?qwe$ pic_url = soup.find_all( 'img' ,src = re. compile (r '^https://cdn.pixabay.com/photo/.*?jpg$' )) #pic_url = pic_node.get_text() #pic_url = re.findall('"https://cdn.pixabay.com/photo/""(.*?)",',html,re.s) print (pic_url) i = 0 #判斷image文件夾是否存在,不存在則創建 if not os.path.exists( 'image' ): os.makedirs( 'image' ) for url in pic_url: img = url[ 'src' ] try : pic = requests.get(img,timeout = 5 ) #超時異常判斷 5秒超時 except requests.exceptions.connectionerror: continue file_name = "image/" + str (i) + ".jpg" #拼接圖片名 print (file_name) #將圖片存入本地 fp = open (file_name, 'wb' ) fp.write(pic.content) #寫入圖片 fp.close() i + = 1 |
代碼是不是很簡單呢 如果你想修改地址 取爬取別的網站 請注意分析下載圖片路徑的共性 并設計合理的正則表達式,否則是無法獲取到圖片路徑的
執行過程截圖:
以上這篇python3.x爬蟲下載網頁圖片的實例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/hanchaobiao/article/details/72873142