爬取http://ycb-benchmarks.s3-website-us-east-1.amazonaws.com/的链接并下载文件

正好就是一个简单的爬虫任务,就分享个代码


#需求:爬取http://ycb-benchmarks.s3-website-us-east-1.amazonaws.com/的链接并下载文件

import requests
from bs4 import BeautifulSoup
import time


def downloadFile(name, url):
    headers = {'Proxy-Connection':'keep-alive'}
    r = requests.get(url, stream=True, headers=headers)
    length = float(r.headers['content-length'])
    f = open(name, 'wb')
    count = 0
    count_tmp = 0
    time1 = time.time()
    for chunk in r.iter_content(chunk_size =1024):
        if chunk:
            f.write(chunk)
            count += len(chunk)
            if time.time() - time1 > 2:
                p = count / length * 100
                speed = (count - count_tmp) / 1024 / 1024 / 2
                count_tmp = count
                print(name + ': ' + formatFloat(p) + '%' + ' Speed: ' + formatFloat(speed) + 'M/S')
                time1 = time.time()
    f.close()

def formatFloat(num):
    return '{:.2f}'.format(num)

#设置url
splice_url = 'http://ycb-benchmarks.s3-website-us-east-1.amazonaws.com/'#需要拼接用来下载的字符
url = 'http://ycb-benchmarks.s3-website-us-east-1.amazonaws.com/'
include_http_str = 'http'
include_scripts_str = 'scripts'
response = requests.get(url)
soup = BeautifulSoup(response.text,'lxml')
for k in soup.find_all('a'):#获取所有的a标签
#处理没用的链接,获得自己需要下载的链接
    if k['href'].find(include_http_str) < 0:
        if k['href'].find(include_scripts_str) < 0:
            cur_str = splice_url + k['href'] #拼接下载好的链接
            cur_count = len(cur_str.split('/')) 
            download_name = cur_str.split('/')[cur_count-1] #设置保存到本地的文件名
            downloadFile(download_name,cur_str) #使用写好的下载脚本直接下载文件



比较简单的代码,但是处理起来还是很方便的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Music 爱好者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值