今天学习的时候遇到了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-8
from urllib.request import urlopen,urlretrieve
from bs4 import BeautifulSoup
import 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 directory
def 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 path
def 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囧,代码也可以,挺简洁的。。。。