• xpath案例-4K图片爬取


    #!/usr/bin/python
    
    #需求:解析下载图片数据 http://pic.netbian.com/4kmeinv/
    import requests
    from lxml import etree 
    import os
    if __name__ == "__main__":
        url = 'http://pic.netbian.com/4kmeinv/'
        headers = {
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2626.106 Safari/537.36'
        }
    
        response = requests.get(url=url,headers=headers)
        #可以手动设定响应数据的编码格式
        # response.encoding = 'utf-8'
        page_text = response.text
    
        #数据解析:src的属性值 alt属性
        tree = etree.HTML(page_text)
        li_list = tree.xpath('//div[@class="slist"]/ul/li')
        # print(li_list)
        
        #创建一个文件夹
        if not os.path.exists('./picLibs'):
            os.mkdir('./picLibs')
    
    
        for li in li_list:
            img_src = 'http://pic.netbian.com'+li.xpath('./a/img/@src')[0]
            img_name = li.xpath('./a/img/@alt')[0]+'.jpg'
            #通用处理处理中文乱码的解决方案
            img_name = img_name.encode('iso-8859-1').decode('gbk')
            # print(img_name,img_src)
            #请求图片进行持久化存储
            img_data = requests.get(url=img_src,headers=headers).content
            
            img_path = 'picLibs/'+img_name
    
            with open(img_path,'wb') as fp:
                fp.write(img_data)
                print(img_name,'下载成功!!!')
    
    
    
  • 相关阅读:
    SQL SERVER DBCC命令参考
    Sqlserver 死锁问题
    收集面试题目DB
    收集面试题目Net
    [转]Virtual PC 2007虚拟机上安装Ubuntu 8.10桌面版
    Tcl/tk基础-2
    【转】内存详解
    [转]C# P2P与NAT技术之二
    泛型跟KeyNotFoundException
    用InstallAware 9制作BDE安装程序
  • 原文地址:https://www.cnblogs.com/gerenboke/p/13389033.html
Copyright © 2020-2023  润新知