# 生成博客文章框架代碼
import datetimeblog_content = f"""# Python如何下載SVG圖片## 引言
SVG(可縮放矢量圖形)作為一種基于XML的矢量圖形格式,在Web開發中廣泛應用。本文將介紹如何使用Python從網絡下載SVG圖片,并提供兩種常見場景的解決方案。## 方案一:直接下載已知URL的SVG文件
```python
import requestsurl = "https://example.com/image.svg"
headers = {'User-Agent': 'Mozilla/5.0'} # 模擬瀏覽器訪問try:response = requests.get(url, headers=headers)response.raise_for_status() # 檢查HTTP狀態碼with open("downloaded_image.svg", "wb") as file:file.write(response.content)print("SVG文件下載成功")
except Exception as e:print(f"下載失敗: {str(e)}")
方案二:從網頁中提取SVG鏈接
from bs4 import BeautifulSoup
import requestsurl = "https://example.com/page-with-svg"
headers = {'User-Agent': 'Mozilla/5.0'}try:response = requests.get(url, headers=headers)soup = BeautifulSoup(response.text, 'html.parser')# 查找所有SVG鏈接(根據實際網頁結構調整選擇器)svg_links = [a['href'] for a in soup.find_all('a', href=True) if a['href'].endswith('.svg')]for idx, link in enumerate(svg_links):svg_data = requests.get(link).contentwith open(f"svg_image_{idx+1}.svg", "wb") as f:f.write(svg_data)print(f"成功下載{len(svg_links)}個SVG文件")
except Exception as e:print(f"處理失敗: {str(e)}")
注意事項
- 遵守目標網站的robots.txt協議
- 處理可能的相對路徑問題
- 添加適當延遲避免觸發反爬機制
- 使用
response.raise_for_status()
進行錯誤檢查
總結
通過本文介紹的兩種方法,開發者可以靈活應對不同場景下的SVG下載需求。建議根據具體網站結構調整選擇器,并始終注意網絡爬蟲的倫理規范。