當前位置:
首頁 >
Python之网络图片爬取
發布時間:2025/3/20
36
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Python之网络图片爬取
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import requests
import os
url = "https://imgsa.baidu.com/exp/w=480/sign=086ffb78b98f8c54e3d3c4270a282dee/d0c8a786c9177f3ec037c19b7dcf3bc79f3d5620.jpg"
root = "D://VscodePy//pics//" # 最后必須加//,否則圖片會保存在VscodePy目錄,pics成為名字開頭的一部分
img_path = root + url.split('/')[-1]
print(img_path)def getHTMLText(url):try:r = requests.get(url, timeout=30)r.raise_for_status() # 如果不是200,引發HTTPError異常# print(r.content)if not os.path.exists(root):os.mkdir(root) # 若不存在路徑則創建if not os.path.exists(img_path): # 若圖片文件不存在with open(img_path, "wb") as f: # 為什么不能是root?而是img_path# 因為它指的是文件名,可換成要保存的路徑+//abc.jpgf.write(r.content)f.close()print("圖片爬取成功!")else:print("圖片已存在!")except:print("產生異常")if __name__ == "__main__":getHTMLText(url)
?
總結
以上是生活随笔為你收集整理的Python之网络图片爬取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python爬取京东商品
- 下一篇: Python爬取淘宝商品价格销量信息