xpath crawls 4K landscape pictures

Connect to a blog and post a few more practical examples to get a better understanding of the use of xpath.
Crawl the 4K landscape image under http://pic.netbian.com/4kfengjing and upload the
code


```python
import requests
import os
from lxml import etree
if __name__=="__main__":
    if not os.path.exists('./4K风景'):
        os.mkdir('./4K风景')
    headers = {
    
    
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3947.100 Safari/537.36'
    }
    url = 'http://pic.netbian.com/4kfengjing/'
    page_text = requests.get(url=url,headers=headers).text
    #实例化对象
    tree = etree.HTML(page_text)
    li_list = tree.xpath('//div[@class="slist"]//li')
    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')
        #获取图片链接并进行永久化存储
        img_data= requests.get(url=img_src,headers=headers).content
        img_path= '4K风景/'+img_name
        with open(img_path,'wb') as fp:
            fp.write(img_data)
            print(img_name,'下载成功!!')
结果存放于新建的文件夹下
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200513135134736.png)

Guess you like

Origin blog.csdn.net/qwerty1372431588/article/details/106096648
Recommended