urlretrieve
来源:互联网 发布:淘宝的二手手机可靠吗 编辑:程序博客网 时间:2024/05/17 21:34
今天学习的时候遇到了urlretrieve这个函数,呵,有点意思。这里简单记录下我的学习过程。
想通过net下载媒体数据,也就是含有src属性的标签的对应的文件。例如jpg,js,html之类的。
from urllib.request import urlopen,urlretrieve def getMeadiaData(): url='http://pythonscraping.com/' html=urlopen(url) bsObj=BeautifulSoup(html.read(),'lxml') downloadList=bsObj.findAll(src=True)
这里的downloadList就是所有包含src的连接,那么我们的任务是要将src
提取出来,并下载到本地(你也可以保存到数据库中)。
有了链接,轮到urlretrieve()上场了,简单连接urlretrieve,
urlretrieve(url, filename=None, reporthook=None, data=None)¶
url:需要下载文件的链接
filename:存放的地址(文件名)
reporthook:回调函数
data:post时传送的数据
上代码:
#!user/bin/python#encoding:utf-8from urllib.request import urlopen,urlretrievefrom bs4 import BeautifulSoupimport os#get the dirname of the download work#if html,create a html directory#if js ,create a js directory#if img ,create a img directorydef getDownloadPath(link): home=r'C:\Users\Yourname\Desktop\study\pyprojects\spyder' os.chdir(home) path=link.split('/')[-1] if '?' in path: path=path.split('?')[0] dir=path.split('.')[-1] if not os.path.exists(dir): os.mkdir(dir) os.chdir(dir) return pathdef cbf(a,b,c): ''' a:已经下载的数据块 b:数据块的大小 c:远程文件的大小 ''' per = 100.0 * a * b / c if per > 100 : per = 100 print('%.2f%%'%per)def getMediaData(): url='http://pythonscraping.com/' html=urlopen(url) bsObj=BeautifulSoup(html.read(),'lxml') downloadList=bsObj.findAll(src=True) for download in downloadList: link=download['src'] urlretrieve(link,getDownloadPath(link),cbf)getMediaData()
这里使用了毁掉函数来显示下载进度,总共下载了8个文件,包含html,img和js.并且存在本地相应的文件夹内结果部分截图: 传不上来 o(╯□╰)o囧,代码也可以,挺简洁的。。。。
0 0
- urlretrieve
- urllib.urlretrieve
- urllib.urlretrieve()
- python urlretrieve
- urllib.urlretrieve()
- python3 爬虫 urlretrieve
- urlretrieve方法的使用
- python3的urlretrieve使用方法
- urlretrieve下载的问题
- python urllib urlretrieve学习使用
- Python中urllib的urlretrieve
- urllib中的urlopen()及urlretrieve()
- Python urllib模块urlretrieve()详解
- 关于python 中的 urlretrieve() 函数
- python学习笔记之url.urlretrieve
- urllib.urlretrieve下载文件不可用原因
- Python urllib的urlretrieve()函数解析
- Python urllib模块urlopen()与urlretrieve()详解
- Stateflow 状态机是怎么代码实现的
- MySQL key_len 大小的计算
- 《Java 编程思想》-第3章 操作符 笔记
- 获得泛型(generic class)参数类型T的实际类型(actual type)
- The absolut uri: http://java.sun.com/jsp/jstl/core cannot be resolved
- urlretrieve
- Java 多线程:join
- 学习笔记--mysql索引(五) 聚簇索引和覆盖索引
- ArchLinux安装与配置
- 转给六年后的我们
- 控制easyui datagrid 显示和隐藏的正确方法
- 关于pyQT5 + VTK7 的一个实现案例
- Android 数据库升级保留原数据不丢
- HTML5学习随记2⃣️