Python使用BeautifulSoup开发爬虫时如何实现实时进度条展示?
批量爬取实时进度实现方案
你之前使用progressbar未达到预期效果,通常是未将进度条更新逻辑和批量爬取的任务计数绑定,以下提供两种可直接落地的实现方案:
方案1:使用tqdm实现(爬虫场景最常用,代码更简洁)
tqdm是当前Python爬虫场景适配度最高的进度条库,支持自动计算爬取速度、剩余时间等信息。
安装依赖
pip install tqdm
可运行示例代码
import requests from bs4 import BeautifulSoup from tqdm import tqdm import time # 单页爬取逻辑封装 def crawl_single_page(url): # 原代码中re是正则标准库的常用命名,避免冲突改为resp resp = requests.get(url) src = resp.content soup = BeautifulSoup(src, "html.parser") tags = soup.find_all("span", {"class" : "styles__children--21o3C"}) # 模拟网络请求延迟,测试进度条时可以打开 # time.sleep(1) return tags if __name__ == "__main__": # 替换为你实际需要爬取的所有url列表 target_urls = [ "https://www.redbubble.com/i/iphone-case/What-A-Time-To-Be-Alive-by-DinoMike/36490886.RIOBD", # 其余待爬url放在这里 ] total_count = len(target_urls) # 用tqdm包裹待爬列表即可自动生成实时进度条 for url in tqdm(target_urls, total=total_count, desc="爬取进度"): page_tags = crawl_single_page(url) # 这里添加你后续的数据存储、处理逻辑 # print(page_tags)
方案2:使用progressbar2实现(适配你之前尝试的模块)
如果你希望继续使用progressbar相关模块,可以使用如下实现:
安装依赖
pip install progressbar2
可运行示例代码
import requests from bs4 import BeautifulSoup import progressbar import time def crawl_single_page(url): resp = requests.get(url) src = resp.content soup = BeautifulSoup(src, "html.parser") tags = soup.find_all("span", {"class" : "styles__children--21o3C"}) return tags if __name__ == "__main__": target_urls = [ "https://www.redbubble.com/i/iphone-case/What-A-Time-To-Be-Alive-by-DinoMike/36490886.RIOBD", # 其余待爬url放在这里 ] total_count = len(target_urls) # 初始化进度条组件 bar = progressbar.ProgressBar(maxval=total_count, widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage(), ' | ', progressbar.ETA()]) bar.start() for index, url in enumerate(target_urls): page_tags = crawl_single_page(url) # 每爬完一页更新进度条 bar.update(index+1) # 后续处理逻辑 bar.finish()
注意事项
- 可自定义进度条显示内容:tqdm支持通过
set_description()方法实时显示当前爬取的页面特征、成功/失败计数等信息。 - 建议在爬取逻辑中添加异常捕获,避免单页请求失败导致整个程序终止,同时可以统计失败任务数量展示在进度条中。
- 请勿使用
re作为requests返回值的变量名,避免和Python标准库re(正则表达式模块)命名冲突。
内容的提问来源于stack exchange,提问作者iso22
相关产品推荐
相关产品推荐

