python实现从网站XKCD下载全部漫画

import requests,bs4,os


url =  'https://xkcd.com/'




#os.makedirs('xkcd',exist_ok=True)#本地目录前创建保存漫画的文件夹
i=0#下载漫画计数


while not url.endswith('#'):
    #下载漫画网页,并匹配查找漫画下载路径
    res = requests.get(url)    
    try:
        resImage.raise_for_status()
    except Exception as exc:
        print('There was a problem:%s'%(exc))
        
    Soup = bs4.BeautifulSoup(res.text)
    comicElems = Soup.select('div#comic img')
    print(comicElems[0])


    if comicElems == []:
        print('Could not find comic image!')
    else:
        comicUrl = 'http:'+str(comicElems[0].get('src'))#拼接漫画下载路径
        print('Downing image %s....'%(comicUrl))
        resImage = requests.get(comicUrl)
        try:
            resImage.raise_for_status()
        except Exception as exc:
            print('There was a problem:%s'%(exc))
        
        #下载漫画存放在文件picturer中


        openFile = open('C:\\Users\\Nick\\Desktop\\python\\drawing\\2\\picture\\'+str(i)+'.png','ab')#下载并重新命名
        i = i+1
        for chunk in resImage.iter_content(10000):
            openFile.write(chunk)
        openFile.close()
        
    #拼接上一页网页路径    
    prevLink = Soup.select('a[rel="prev"]')[0]
    url = 'https://xkcd.com/'+str(prevLink.get('href'))


print("Done!")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值