美文网首页程序员
小福利,教大家用python抓取妹子图2020-05-18

小福利,教大家用python抓取妹子图2020-05-18

作者: python小哥哥2020 | 来源:发表于2020-05-18 19:31 被阅读0次

    大家好,我是天空之城,今天带来一个小福利,教大家用python抓取妹子图。话不多说,上代码。

    import requests,re,lxml
    from lxml import etree
    
    class Spider(object):
        def __init__(self):
            self.headers = {
                'Referer': 'https://www.mzitu.com',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:46.0) Gecko/20100101 Firefox/46.0',
                'cookie': 'Hm_lvt_cb7f29be3c304cd3bb0c65a4faa96c30=1589688375; Hm_lpvt_cb7f29be3c304cd3bb0c65a4faa96c30=1589693220'
            }
    
    
        def getpage(self):
            for i in range(100):
                url = 'https://www.mzitu.com/page/{}/'.format(str(i))
                res=requests.get(url,headers=self.headers)
                print(res.status_code)
                res1=res.text
                html = etree.HTML(res1)
                self.getdata(html)
    
        def getdata(self,html):
    
            titles=html.xpath('//ul[@id="pins"]/li/a/img/@alt')
            links=html.xpath('//ul[@id="pins"]/li/a/img/@data-original')
            for title,link in zip(titles,links):
                pic_name = title + '.jpg'
                res_pic = requests.get(url=link, headers=self.headers)
                try:
                    with open(pic_name, 'wb') as f:
                        f.write(res_pic.content)
                except Exception:
                    pass
                  
    spider=Spider()
    spider.getpage()
    
    

    ==============================================================
    *先来到妹子图主页,https://www.mzitu.com(第一次requests请求网址),分析发现有很多类别,右击查看元素获得网址,选择第一个类别来到[https://www.mzitu.com/231755](第二次requests地址),右击查看元素,再点击一张图片右击找到图片地址<img src="https://i3.mmzztt.com/2020/05/16a01.jpg" alt="周于希" width="700" height="1050">,其中src是图片地址,而alt是图片名称,直接用xpath获得名称和地址,直接带上图片名称保存图片(二进制数据),思路就是这样。这个面向对象是参考别人的代码写的,我自己写的是面向过程的。

    相关文章

      网友评论

        本文标题:小福利,教大家用python抓取妹子图2020-05-18

        本文链接:https://www.haomeiwen.com/subject/ouupohtx.html