当前位置: 移动技术网 > IT编程>脚本编程>Python > python网络爬虫与信息采取之下载存储数据(一)-----下载储存媒体文件模板

python网络爬虫与信息采取之下载存储数据(一)-----下载储存媒体文件模板

2018年03月21日  | 移动技术网IT编程  | 我要评论

韩国歌词,新兰h文,长城永在我心中

还在为一张张的点下载图片而烦恼吗?请用一个程序员的思路来解决这个问题,下面就是可以节省你大量时间的代码;

存储媒体文件有两种方式:一是只获取URL链接;二是直接把源文件下载下来

下面这个就是直接把源文件下载下来的实例:

其中,

urlretrieve()函数用于下载文件

代码如下:

<span style="font-size:18px;">import os  
from urllib.request import urlretrieve  
from urllib.request import urlopen  
from bs4 import BeautifulSoup  
  
downloadDirectory = "D:\downloaded"  
baseUrl = "https://pythonscraping.com"  
  
  
def getAbsoluteURL(baseUrl, source):  
    if source.startswith("https://www."):  
        url = "https://" + source[11:]  
    elif source.startswith("https://"):  
        url = source  
    elif source.startswith("www."):  
        url = source[4:]  
        url = "https://" + source  
    else:  
        url = baseUrl + "/" + source  
    if baseUrl not in url:  
        return None  
    return url  
  
  
def getDownloadPath(baseUrl, absoluteUrl, downloadDirectory):  
    path = absoluteUrl.replace("www.", "")  
    path = path.replace(baseUrl, "")  
    path = downloadDirectory + path  
    directory = os.path.dirname(path)  
    if not os.path.exists(directory):  
        os.makedirs(directory)  
    return path  
  
  
html = urlopen("https://www.pythonscraping.com")  
bsObj = BeautifulSoup(html)  
downloadList = bsObj.findAll(src=True)  
for download in downloadList:  
    fileUrl = getAbsoluteURL(baseUrl, download["src"])  
    if fileUrl is not None:  
        print(fileUrl)  
  
urlretrieve(fileUrl, getDownloadPath(baseUrl, fileUrl, downloadDirectory))  
</span>  

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网