用python爬虫爬取图片的步骤_python数据爬虫

用python爬虫爬取图片的步骤_python数据爬虫因为平时爱好摄影,所以喜欢看看色影无忌论坛的获奖摄影作品,所以写了个小script用来抓取上面的获奖图片,亲自测试可以使用。#-*-coding:UTF-8-*-#作者RockyChenimportre,urllib,sys,os,time,urllib2,cookielib,stringclassDownload:def__init__(self

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

原文地址: http://www.30daydo.com/article/56

因为平时爱好摄影,所以喜欢看看色影无忌论坛的获奖摄影作品,所以写了个小script用来抓取上面的获奖图片,亲自测试可以使用。

自动抓所有的获奖图片

用python爬虫爬取图片的步骤_python数据爬虫

完整代码: 

#-*-coding=utf-8-*-
__author__ = 'rocchen'
from bs4 import BeautifulSoup
import urllib2,sys,StringIO,gzip,time,random,re,urllib,os
reload(sys)
sys.setdefaultencoding('utf-8')
class Xitek():
    def __init__(self):
        self.url="http://photo.xitek.com/"
        user_agent="Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
        self.headers={"User-Agent":user_agent}
        self.last_page=self.__get_last_page()


    def __get_last_page(self):
        html=self.__getContentAuto(self.url)
        bs=BeautifulSoup(html,"html.parser")
        page=bs.find_all('a',class_="blast")
        last_page=page[0]['href'].split('/')[-1]
        return int(last_page)


    def __getContentAuto(self,url):
        req=urllib2.Request(url,headers=self.headers)
        resp=urllib2.urlopen(req)
        #time.sleep(2*random.random())
        content=resp.read()
        info=resp.info().get("Content-Encoding")
        if info==None:
            return content
        else:
            t=StringIO.StringIO(content)
            gziper=gzip.GzipFile(fileobj=t)
            html = gziper.read()
            return html

    #def __getFileName(self,stream):


    def __download(self,url):
        p=re.compile(r'href="(/photoid/\d+)"')
        #html=self.__getContentNoZip(url)

        html=self.__getContentAuto(url)

        content = p.findall(html)
        for i in content:
            print i

            photoid=self.__getContentAuto(self.url+i)
            bs=BeautifulSoup(photoid,"html.parser")
            final_link=bs.find('img',class_="mimg")['src']
            print final_link
            #pic_stream=self.__getContentAuto(final_link)
            title=bs.title.string.strip()
            filename = re.sub('[\/:*?"<>|]', '-', title)
            filename=filename+'.jpg'
            urllib.urlretrieve(final_link,filename)
            #f=open(filename,'w')
            #f.write(pic_stream)
            #f.close()
        #print html
        #bs=BeautifulSoup(html,"html.parser")
        #content=bs.find_all(p)
        #for i in content:
        #    print i
        '''
        print bs.title
        element_link=bs.find_all('div',class_="element")
        print len(element_link)
        k=1
        for href in element_link:

            #print type(href)
            #print href.tag
        '''
        '''
            if href.children[0]:
                print href.children[0]
        '''
        '''
            t=0

            for i in href.children:
                #if i.a:
                if t==0:
                    #print k
                    if i['href']
                    print link

                        if p.findall(link):
                            full_path=self.url[0:len(self.url)-1]+link
                            sub_html=self.__getContent(full_path)
                            bs=BeautifulSoup(sub_html,"html.parser")
                            final_link=bs.find('img',class_="mimg")['src']
                            #time.sleep(2*random.random())
                            print final_link
                    #k=k+1
                #print type(i)
                #print i.tag
                #if hasattr(i,"href"):
                    #print i['href']
                #print i.tag
                t=t+1
                #print "*"

        '''

        '''
            if href:
                if href.children:
                    print href.children[0]
        '''
            #print "one element link"



    def getPhoto(self):

        start=0
        #use style/0
        photo_url="http://photo.xitek.com/style/0/p/"
        for i in range(start,self.last_page+1):
            url=photo_url+str(i)
            print url
            #time.sleep(1)
            self.__download(url)

        '''
        url="http://photo.xitek.com/style/0/p/10"
        self.__download(url)
        '''
        #url="http://photo.xitek.com/style/0/p/0"
        #html=self.__getContent(url)
        #url="http://photo.xitek.com/"
        #html=self.__getContentNoZip(url)
        #print html
        #'''
def main():
    sub_folder = os.path.join(os.getcwd(), "content")
    if not os.path.exists(sub_folder):
        os.mkdir(sub_folder)
    os.chdir(sub_folder)
    obj=Xitek()
    obj.getPhoto()


if __name__=="__main__":
    main()

详细讲解请移步: 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/193821.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 无键盘屏幕配置树莓派连接WiFi

    无键盘屏幕配置树莓派连接WiFi前言Ubuntu20.04LTS都发布好一段时间了,官方支持RaspberryPi,手痒痒了想试试,结果发现没带miniHDMI的转接线,看了下Ubuntu官方的树莓派安装文档:https://ubuntu.com/tutorials/how-to-install-ubuntu-on-your-raspberry-pi#1-overview可以直接在TF卡根目录下面创建配置文件来实现WiFi连接的.记录一下实操过程Ubuntu20.04LTS系统镜像写入TF卡习惯了先手动下载系统镜像:

    2022年6月13日
  • centos系统不识别u盘_Unable to locate package vim

    centos系统不识别u盘_Unable to locate package vim在修改源后使用sudoapt-getupdate 显示 W:GPGerror:https://mirrors.ustc.edu.cn/kalikali-rollingInRelease:Thefollowingsignaturescouldn’tbeverifiedbecausethepublickeyisnotavailable:…

    2022年10月13日
  • 扩展Python模块系列(二)—-一个简单的例子

    扩展Python模块系列(二)—-一个简单的例子

    2022年3月6日
  • F分布的概率密度函数_F分布的统计量是

    F分布的概率密度函数_F分布的统计量是定义:设X1∼χ2(m),X2∼χ2(n)X_{1}\sim\chi^{2}(m),X_{2}\sim\chi^{2}(n)X1​∼χ2(m),X2​∼χ2(n),X1X_{1}X1​与X2X_{2}X2​相互独立,则称随机变量F=X1/mX2/nF=\frac{X_{1}/m}{X_{2}/n}F=X2​/nX1​/m​服从自由度为mmm及nnn的FFF分布,mmm称为第一自由度,n\boldsymbol{n}n称为第二自由

    2022年10月10日
  • vue pc分辨率自适应(vue页面自适应屏幕分辨率)

    依赖项目基础配置使用vue-cli生成自适应方案核心:阿里可伸缩布局方案lib-flexiblepx转rem:px2rem,它有webpack的loaderpx2rem开始先使用vue脚手架初始化一个webpack项目vueinitwebpack项目名项目初始化好了之后,进入项目目录中(cd项目名)安装lib-flexible和px2rem-loade…

    2022年4月16日
  • VLAN的基本配置_划分不全的例子

    VLAN的基本配置_划分不全的例子1、VLAN基础知识VLAN(VirtualLocalAreaNetwork)的中文名为:“虚拟局域网”,注意和’VPN’(虚拟专用网)进行区分。VLAN是一种将局域网设备从逻辑上划分(不是从物理上划分)成一个个网段,从而实现虚拟工作组的新兴数据交换技术。这一新兴技术主要应用于交换机和路由器中,但主流应用还是在交换机之中。但又不是所有交换机都具有此功能,只有VLAN协议的第三层以上交换机才具有此功能,这一点可以查看相应交换机的说明书即可得知。由于它是从逻辑上划分,而不是从物理上..

    2022年9月19日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号