python 爬虫 抓取网站img图片


from getHtml import getHtmlWinthIp
from getHtml import  getHtml
from bs4 import BeautifulSoup
from urllib import request#为了存储
import os #为了创建文件夹
imgsrcl = []
def getD(url,no):
    html = getHtmlWinthIp(url)

    soup = BeautifulSoup(html,'html.parser')

    #寻找parent
    parent = soup.find(id='content').find('ul')
    #找到所有的li

    lis = parent.find_all('li',limit=no)

    #新建列表存储所有的src

    for each in lis:
        #each.find('img').attrs这是所有img的属性组成的字典
        src = each.find('img').attrs['src']#读取字典的src
        imgsrcl.append(src)#添加到总的列表


    # os.mkdir()#创建文件夹
    # os.chdir()#改变文件路径
    # os.path.exists()#判断是否已经存在某文件夹
    
def store():
    if os.path.exists('范冰冰2'):
        os.chdir('范冰冰2')
    else:
        os.mkdir('范冰冰2')
        os.chdir('范冰冰2')
        
    # 存储
    for i, v in enumerate(imgsrcl):
        request.urlretrieve(v, str(i + 1) + '.jpg')
def main(n):
    for index in range(30,n+31,30) :
        url = 'https://movie.douban.com/celebrity/1050059/photos/?type=C&start='+str(index-30)+'&sortby=like&size=a&subtype=a'
        print("正在爬取第" + str(index//30) + "页")
        if  n%index!=0:
            no=n%index
            getD(url,no)
        else:
            getD(url,30)

    store()


#传入多少就爬取多少张
if __name__ == '__main__':
    main(48)

猜你喜欢

转载自blog.csdn.net/qq_40243365/article/details/83003257