python requests下载获取到的图片地址_python+requests抓取页面图片

前言:

学完requests库后,想到可以利用python+requests爬取页面图片,想到实战一下。依照现在所学只能爬取图片在html页面的而不能爬取由JavaScript生成的图片,所以我选取饿了打开下面这个页面http://p.weather.com.cn/2017/06/2720826.shtml#p=7

案例步骤:

1.利用requests库,调用requests库中的get()方法,打开需要爬去的页面url,返回页面内容,下面是自定义的打开页面的方法

def load_page(url):

response=requests.get(url)

data=response.content

return data

2.用正则表达式去匹配页面的图片链接,匹配成功后,把图片下载下来,保存到对应的文件位置,下面是自定义的保存图片方法

def get_image(html):

regx=r'http://[\S]*jpg'

pattern=re.compile(regx)

get_images=re.findall(pattern,repr(html))

num=1

for img in get_images:

image=load_page(img)

with open('./spider_picture/%s.jpg' % num,'wb') as fb:

fb.write(image)

print("正在下载第%s张图片" %num)

num=num+1

print("下载完成!")

完整案例源码:

# coding:utf-8

# 引入requests包和正则表达式包re

import requests

import re

# 自定义下载页面函数

def load_page(url):

response=requests.get(url)

data=response.content

return data

# 自定义保存页面图片函数

def get_image(html):

regx=r'http://[\S]*jpg' # 定义图片正则表达式

pattern=re.compile(regx) # 编译表达式构造匹配模式

get_images=re.findall(pattern,repr(html)) # 在页面中匹配图片链接

num=1

# 遍历匹配成功的链接

for img in get_images:

image=load_page(img) #根据图片链接,下载图片链接

# 将下载的图片保存到对应的文件夹中

with open('./spider_picture/%s.jpg' % num,'wb') as fb:

fb.write(image)

print("正在下载第%s张图片" %num)

num=num+1

print("下载完成!")

# 定义爬取页面的链接

url ='http://p.weather.com.cn/2017/06/2720826.shtml#p=7'

# 调用load_page函数,下载页面内容

html = load_page(url)

# 在页面中,匹配图片链接,并将图片下载下来,保存到对应文件夹

get_image(html)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值