python用requests模块下载图片

用requests.get()方法获取网页代码

用beautifulsoup模块解析出图片地址

再用requests模块以图片地址为参数,再发一次请求。

with open as f 以二进制保存图片信息。img.content

import requests
from bs4 import BeautifulSoup as bs 

url='http://bbs.fengniao.com/forum/10957178_p97726260.html#post97726260'     
r=requests.get(url)
html=bs(r.text,'html.parser')  #获取页面源代码,

div_list=html.find_all('div',class_='img')           #取得所有含有图片的div,存入列表
i=1
for div in div_list:
    a=div.find('a')             #在每个div中找到a标签
    img=a.find('img')           #在img标签中找到a标签
    src=img.get('src')          #在img标签中获得src属性,即图片的真实地址
    img_url=src.split('?')[0]   #图片地址中有“?”加上一些无聊的后辍,去掉它,否则不能原尺寸显示

    #保存图片,
    with open('D:/study/b{}.jpg'.format(i),'wb') as f:
        img=requests.get(img_url)  #还得用图片地址再发一遍请求
        f.write(img.content)       #以二进制方式写入文件
    i+=1
    
print('ok')

保存图片好麻烦呀

猜你喜欢

转载自www.cnblogs.com/jm7612/p/12402228.html