其他分享
首页 > 其他分享> > 爬虫学习一:bs下载图片+进度条

爬虫学习一:bs下载图片+进度条

作者:互联网

bs下载图片+进度条

刚开始学习爬虫,当然是从简单地开始,没有什么比爬点美女图片更能提起兴趣的了,这次要爬的网站是彼岸网,不废话,上代码

import requests
from bs4 import BeautifulSoup
from tqdm import tqdm

# 通过url解析获得网页内容
def parse_html(url):
    header = {
        'User - Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/'
                        '94.0.4606.81 Safari/537.36'
    }
    res = requests.get(url, headers=header)
    return res.content.decode('utf-8', 'ignore')

# 通过bs在网页代码里找到图片网址 
def get_url_list(content):
    bs = BeautifulSoup(content, 'html.parser')
    img_list = bs.find_all('img')
    return [i.get('src') for i in img_list]

# 通过图片网址 下载图片
def download_img(url):
	# 因为网页里图片网址是不全的,首先要补全,可以通过很多方法获得,这里省事了,直接字符串拼接
    hole_url = 'https://pic.netbian.com' + url
    cont = requests.get(hole_url).content
    with open('1/{}.jpg'.format(url.split("/")[-1]), 'wb') as f:
        f.write(cont)


if __name__ == '__main__':
    url = 'https://pic.netbian.com/4kmeinv/'
    list = get_url_list(parse_html(url))
	# 使用tqdm,显示进度条
    d = {'loss': 0.2, 'learn': 0.8}
    for l in tqdm(list, desc='进行中', ncols=10):
        download_img(l)

心得

一、bs用法很灵活,非常灵活
二、解析html时候字符编号是很容易报错的地方,刚开始写res.content.decode(‘utf-8’) 总是报错,后来查攻略,发现写res.content.decode(‘utf-8’, ‘ignore’)才行
三、tqdm只是显得高大上一点,但要注意导入时要写from tqdm import tqdm,如果直接写 import tqdm会一直报错
四、代码是自己写的一个简单练习,仅用作记录,后期完善,加入翻页和其他功能

标签:tqdm,img,进度条,url,list,爬虫,content,bs
来源: https://blog.csdn.net/weixin_43085185/article/details/122531231