共計 845 個字符,預計需要花費 3 分鐘才能閱讀完成。
要實現批量爬取圖片,可以使用 Python 的 requests 庫和 BeautifulSoup 庫來爬取網頁內容,然后使用正則表達式或者其他方法提取出圖片的 url,最后使用 requests 庫下載圖片。
下面是一個基本的示例代碼:
import requests
from bs4 import BeautifulSoup
import os
# 定義要爬取的網頁 URL
url = 'http://example.com'
# 發送 GET 請求獲取網頁內容
response = requests.get(url)
html = response.text
# 創建保存圖片的目錄
os.makedirs('images', exist_ok=True)
# 使用 BeautifulSoup 解析網頁內容
soup = BeautifulSoup(html, 'html.parser')
# 查找所有的圖片標簽
img_tags = soup.find_all('img')
# 遍歷圖片標簽,獲取圖片的 URL 并下載
for img_tag in img_tags:
img_url = img_tag['src']
img_name = img_url.split('/')[-1] # 獲取圖片文件名
img_path = os.path.join('images', img_name) # 拼接圖片保存路徑
# 發送 GET 請求下載圖片
img_response = requests.get(img_url)
with open(img_path, 'wb') as f:
f.write(img_response.content)
print(f'Downloaded {img_path}')
這段代碼會從指定的網頁 URL 中爬取所有的圖片,并保存到當前目錄下的 "images" 文件夾中。可以根據具體需求適當修改代碼。
丸趣 TV 網 – 提供最優質的資源集合!
正文完