python下载图片怎么保存_Python爬虫获取图片并下载保存至本地

这篇文章主要介绍了关于Python爬虫获取图片并下载保存至本地,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

1、抓取煎蛋网上的图片。

2、代码如下:

import urllib.request

import os

#to open the url

def url_open(url):

req=urllib.request.Request(url)

req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.3; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0')

response=urllib.request.urlopen(url)

html=response.read()

return html

#to get the num of page like 1,2,3,4...

def get_page(url):

html=url_open(url).decode('utf-8')

a=html.find('current-comment-page')+23 #add the 23 offset th arrive at the [2356]

b=html.find(']',a)

#print(html[a:b])

return html[a:b]

#find the url of imgs and return the url of arr

def find_imgs(url):

html=url_open(url).decode('utf-8')

img_addrs=[]

a=html.find('img src=')

while a!=-1:

b=html.find('.jpg',a,a+255) # if false : return -1

if b!=-1:

img_addrs.append('http:'+html[a+9:b+4])

else:

b=a+9

a=html.find('img src=',b)

#print(img_addrs)

return img_addrs

#print('http:'+each)

#save the imgs

def save_imgs(folder,img_addrs):

for each in img_addrs:

filename=each.split('/')[-1] #get the last member of arr,that is the name

with open(filename,'wb') as f:

img = url_open(each)

f.write(img)

def download_mm(folder='mm',pages=10):

os.mkdir(folder)

os.chdir(folder)

url='http://jandan.net/ooxx/'

page_num=int(get_page(url))

for i in range(pages):

page_num -= i

page_url = url + 'page-' + str(page_num) + '#comments'

img_addrs=find_imgs(page_url)

save_imgs(folder,img_addrs)

if __name__ == '__main__':

download_mm()

相关推荐:

以上就是Python爬虫获取图片并下载保存至本地的详细内容,更多请关注php中文网其它相关文章!

article_wechat2021.jpg?1111

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Python爬取百度图片保存的示例代码: ```python # 导入依赖库 import requests import re import os # 设置搜索关键字 keyword = "美食" # 设置图片保存路径 save_path = "./images/" # 构造百度图片搜索的URL url = "https://image.baidu.com/search/index?tn=baiduimage&word={}".format(keyword) # 发送HTTP请求并获取响应 response = requests.get(url) # 使用正则表达式从响应内容中提取图片URL列表 img_urls = re.findall('"objURL":"(.*?)",', response.text, re.S) # 遍历图片URL列表并下载保存图片 for i, img_url in enumerate(img_urls): try: # 发送HTTP请求并获取响应 response = requests.get(img_url, timeout=10) # 设置图片保存路径 img_path = os.path.join(save_path, "{}.jpg".format(i)) # 保存图片 with open(img_path, "wb") as f: f.write(response.content) print("成功下载第{:>3d}张图片!".format(i+1)) except Exception as e: print("下载第{:>3d}张图片失败:{}".format(i+1, e)) ``` 解释一下上述代码的主要步骤: 1. 设置搜索关键字和图片保存路径 2. 构造百度图片搜索的URL 3. 发送HTTP请求并获取响应 4. 使用正则表达式从响应内容中提取图片URL列表 5. 遍历图片URL列表并下载保存图片 需要注意的是,这种方式只是简单的使用正则表达式从响应内容中提取图片URL,而没有使用任何API,因此可能存在一些不稳定性和容易被反爬虫机制封禁的风险。建议在使用时注意合理使用代理、设置请求头等防反爬措施。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值