python爬虫获取图片基础教程

结合前述第一个博客,简单的一个爬取图片的代码

环境:

anaconda+python 3.6.1

import requests
from lxml import etree

def get_url():
    url='http://image.so.com/'
    r=requests.get(url)
    r.encoding = 'UTF-8'
    #print(r.text)
    html=etree.HTML(r.text)
    imgs = html.xpath('//div[@class="block"]//a/img/@src')  
    j=0
    l=[]
    for i in range(1,100):
        l.append(i)
    for img in imgs:        
        url_img=img.strip()
        print(url_img)
        name=str(l[j])                
        savefile(url_img,name)
        j+=1
        
def savefile(url_img,name):
    print("保存")
    img = requests.get(url_img)   
    file_name = name + '.jpg'        
    f = open('F://python//test//爬虫学习//保存美女图片' + '/'+file_name, 'ab')
    print('开始保存图片')
    f.write(img.content)
    f.close()    
    
get_url()  
savefile()

欢迎留言,多多交流

你可能感兴趣的:(python爬虫获取图片基础教程)