1. if __name__ == "__main__":
    2. url = 'http://pic.netbian.com/4kmeinv/'
    3. headers = {
    4. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) '
    5. 'Chrome/73.0.3683.103 Safari/537.36 '
    6. }
    7. response = requests.get(url=url, headers=headers)
    8. # 手动设定响应数据的编码格式
    9. # response.encoding = 'utf-8'
    10. page_text = response.text
    11. # 数据解析:src的属性值 alt属性
    12. tree = etree.HTML(page_text)
    13. li_list = tree.xpath('//div[@class="slist"]/ul/li')
    14. # 创建一个文件夹
    15. if not os.path.exists('./picLibs'):
    16. os.mkdir('./picLibs')
    17. for li in li_list:
    18. img_src = 'http://pic.netbian.com' + li.xpath('./a/img/@src')[0]
    19. img_name = li.xpath('./a/img/@alt')[0] + '.jpg'
    20. # 通用处理中文乱码的解决方案
    21. img_name = img_name.encode('iso-8859-1').decode('gbk')
    22. # print(img_name,img_src)
    23. # 请求图片进行持久化存储
    24. img_data = requests.get(url=img_src, headers=headers).content
    25. img_path = 'picLibs/' + img_name
    26. with open(img_path, 'wb') as fp:
    27. fp.write(img_data)
    28. print(img_name, '下载成功!!!')